python批量更改文件名称
时间: 2025-06-29 12:04:14 浏览: 10
### 使用Python批量修改文件名
在文件管理和数据处理领域,批量修改文件名是一个常见的任务。Python凭借其强大而灵活的功能以及丰富的标准库支持,成为执行此类操作的理想选择。
#### 添加前缀至所有文件名称
对于希望给定目录下所有的文件名字添加相同前缀的需求,下面提供了一种实现方式:
```python
import os
def add_prefix_to_filenames(directory, prefix):
"""向指定目录内的所有文件名之前追加固定的字符串"""
for filename in os.listdir(directory):
source = os.path.join(directory, filename)
destination = os.path.join(directory, f"{prefix}{filename}")
try:
os.rename(source, destination)
print(f'Renamed {source} to {destination}')
except Exception as e:
print(f'Failed renaming {source}:', str(e))
# 调用函数并传入目标路径和想要增加的前缀
add_prefix_to_filenames('path/to/your/directory/', 'newPrefix_')
```
此段代码利用`os.listdir()`获取待处理文件列表,并通过循环迭代每一个条目完成重命名动作[^1]。
#### 替换特定字符串于文件名之中
当面临需要将现有文件名里的某些部分替换成其他内容的情况时,则可采用如下方法:
```python
import os
def replace_string_in_filenames(directory, old_str, new_str):
"""替换指定目录内所有文件名中存在的旧字符串为新的字符串"""
for filename in os.listdir(directory):
if old_str in filename:
src = os.path.join(directory, filename)
dst = os.path.join(directory, filename.replace(old_str, new_str))
try:
os.rename(src, dst)
print(f'Replaced "{old_str}" with "{new_str}" in {src}, now it is named {dst}.')
except Exception as e:
print(f'Error occurred while replacing string in {src}: ', str(e))
replace_string_in_filenames('/path/to/folder/', '_OLD_', '_NEW_')
```
上述例子展示了如何遍历指定文件夹中的每一项,检查它们的名字是否含有要被替代的部分;如果有匹配的结果就调用`rename()`来进行更改[^2]。
#### 按照顺序编号重新排列文件名
有时还需要按照一定的规律(例如连续整数)来调整一系列同类型文档的称呼。这里给出一个简单的解决方案:
```python
import os
def number_files_sequentially(directory, start=1):
"""对指定目录下的文件按序号进行重命名."""
files = sorted([f for f in os.listdir(directory) if not f.startswith('.')]) # 排除隐藏文件
for index, filename in enumerate(files, start=start):
ext = '' if '.' not in filename else '.' + filename.split('.')[-1]
new_filename = f'{index:03d}{ext}' # 假设三位数字作为序列号
full_old_path = os.path.join(directory, filename)
full_new_path = os.path.join(directory, new_filename)
try:
os.rename(full_old_path, full_new_path)
print(f'Modified name from {full_old_path} -> {full_new_path}')
except OSError as err:
print(err)
number_files_sequentially("/path/to/files/", 1)
```
这段程序首先收集了非隐藏类型的全部项目,接着依据自然排序后的次序依次赋予递增式的索引标签[^3]。
阅读全文
相关推荐
















