以下是一个Python示例代码,用于遍历目录中的文件并提取文件名来替换现有文件中的字符串:
import os
def traverse_directory(directory):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
replace_string(file_path)
def replace_string(file_path):
file_name = os.path.basename(file_path)
new_file_name = file_name.replace("old_string", "new_string")
if new_file_name != file_name:
new_file_path = os.path.join(os.path.dirname(file_path), new_file_name)
os.rename(file_path, new_file_path)
print(f"Renamed file: {file_path} -> {new_file_path}")
# 替换指定目录下的文件
directory = "path/to/directory"
traverse_directory(directory)
注意,上述代码使用os.walk
函数来遍历指定目录下的文件和子目录。对于每个文件,我们使用os.path.basename
函数获取文件名,然后使用str.replace
方法替换字符串(在示例中替换"old_string"为"new_string")。如果替换后的文件名与原文件名不同,我们使用os.rename
函数来重命名文件,并输出重命名的文件路径。
请将path/to/directory
替换为实际的目录路径。