在Python中,您可以使用`os`模块来批量重命名文件。以下是一些示例代码,展示了如何使用`os.listdir`和`os.rename`函数来重命名文件:
示例1:给指定文件添加前缀
```python
import os
def add_prefix_files(path, prefix):
for old_name in os.listdir(path):
if old_name.endswith('.txt') and old_name != 'script_name.txt': 防止脚本文件被重命名
new_name = prefix + old_name
old_path = os.path.join(path, old_name)
new_path = os.path.join(path, new_name)
os.rename(old_path, new_path)
print(f"{old_name} has been renamed to {new_name}")
使用示例
add_prefix_files('Test2', 'test-')
示例2:替换文件名中的指定字符串
```python
import os
def batch_rename(directory, old_str, new_str):
for filename in os.listdir(directory):
if old_str in filename:
new_filename = filename.replace(old_str, new_str)
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"Renamed {filename} to {new_filename}")
使用示例
batch_rename('path/to/directory', 'old_string', 'new_string')
示例3:按顺序重命名文件
```python
import os
def reName(dirname):
count = 0
for cur_file in os.listdir(dirname):
count += 1
oldDir = os.path.join(dirname, cur_file)
filetype = os.path.splitext(cur_file)
newDir = os.path.join(dirname, str(count) + filetype)
os.rename(oldDir, newDir)
print(f"Renamed {oldDir} to {newDir}")
使用示例
reName('path/to/directory')
示例4:自定义文件名格式
```python
import os
def doc_rename(path_src, path_dst, begin_num, rename_format):
for i in os.listdir(path_src):
doc_src = os.path.join(path_src, i)
doc_name = rename_format.format(begin_num, os.path.splitext(i)[-1])
new_path = os.path.join(path_dst, doc_name)
os.rename(doc_src, new_path)
print(f"Renamed {doc_src} to {new_path}")
begin_num += 1
使用示例
doc_rename('path/to/source/folder', 'path/to/destination/folder', 1, '报告-第{}份{}'.format)
示例5:批量重命名图片文件
```python
import os
class ImageRename():
def __init__(self, path):
self.path = path
def rename(self):
filelist = os.listdir(self.path)
total_num = len(filelist)
i = 0
for item in filelist:
if item.endswith('.jpg'):
src = os.path.join(os.path.abspath(self.path), item)
dst = os.path.join(os.path.abspath(self.path), f'0000{str(i).zfill(4)}.jpg')
os.rename(src, dst)
print(f"Converting {src} to {dst} ...")
i += 1
print(f"Total {total_num} to rename and converted {i} jpgs")
使用示例
newname = ImageRename('/path/to/image/folder')
newname.rename()
请根据您的具体需求选择合适的示例代码,并确保在运行代码前备份您的文件,以防万一出现错误。如果您有任何其他问题或