遍历文件夹将指定文件名改为另一个指定文件名代码
时间: 2024-02-13 09:09:56 浏览: 37
以下是Python代码示例,可以实现遍历指定文件夹并将指定文件名改为另一个指定文件名:
```python
import os
def rename_files(path, old_filename, new_filename):
for root, dirs, files in os.walk(path):
for file in files:
if file == old_filename:
file_path = os.path.join(root, file)
new_file_path = os.path.join(root, new_filename)
os.rename(file_path, new_file_path)
print(f"{file_path} renamed to {new_file_path}")
# 示例:将文件夹 D:/test 中所有文件名为 "old.txt" 的文件改为 "new.txt"
path = "D:/test"
old_filename = "old.txt"
new_filename = "new.txt"
rename_files(path, old_filename, new_filename)
```
在示例代码中,`os.walk()` 方法可以遍历指定目录下的所有子目录和文件,然后使用 `os.rename()` 方法将文件名改为新的名称。其中,`file_path` 表示原文件的完整路径,`new_file_path` 表示新文件的完整路径。最后,使用 `print()` 方法输出修改后的文件名。