在Python中,你可以使用os
模块来批量修改文件名。以下是一个简单的示例,该示例将指定目录下的所有.txt
文件的文件名中的old
替换为new
:
![图片[1]_Python实现批量修改文件名的方法_知途无界](https://zhituwujie.com/wp-content/uploads/2024/04/4a47a0db6e20240415111545.png)
import osdef batch_rename_files(directory, old_substring, new_substring):for filename in os.listdir(directory):if filename.endswith(".txt") and old_substring in filename:new_filename = filename.replace(old_substring, new_substring)source = os.path.join(directory, filename)destination = os.path.join(directory, new_filename)# 重命名文件os.rename(source, destination)print(f"Renamed '{filename}' to '{new_filename}'")# 使用函数batch_rename_files("/path/to/your/directory", "old", "new")import os def batch_rename_files(directory, old_substring, new_substring): for filename in os.listdir(directory): if filename.endswith(".txt") and old_substring in filename: new_filename = filename.replace(old_substring, new_substring) source = os.path.join(directory, filename) destination = os.path.join(directory, new_filename) # 重命名文件 os.rename(source, destination) print(f"Renamed '{filename}' to '{new_filename}'") # 使用函数 batch_rename_files("/path/to/your/directory", "old", "new")import os def batch_rename_files(directory, old_substring, new_substring): for filename in os.listdir(directory): if filename.endswith(".txt") and old_substring in filename: new_filename = filename.replace(old_substring, new_substring) source = os.path.join(directory, filename) destination = os.path.join(directory, new_filename) # 重命名文件 os.rename(source, destination) print(f"Renamed '{filename}' to '{new_filename}'") # 使用函数 batch_rename_files("/path/to/your/directory", "old", "new")
在这个示例中,batch_rename_files
函数接受三个参数:要修改的文件的目录、要在文件名中查找并替换的子字符串以及新的子字符串。函数首先列出目录中的所有文件,然后检查每个文件的扩展名是否为.txt
以及文件名中是否包含要替换的子字符串。如果满足这些条件,则使用os.rename
函数重命名文件。
注意:请确保替换"/path/to/your/directory"
为你想要修改的文件的实际目录路径。此外,这个脚本会直接在原目录上进行操作,如果你希望保留原文件,你需要在重命名前复制文件到新的位置。
还需要注意的是,此脚本不会处理文件名冲突。也就是说,如果新文件名已经存在,os.rename
函数将抛出一个错误。如果你需要处理这种情况,你可能需要在重命名前检查新文件名是否已经存在,并相应地处理。
© 版权声明
文中内容均来源于公开资料,受限于信息的时效性和复杂性,可能存在误差或遗漏。我们已尽力确保内容的准确性,但对于因信息变更或错误导致的任何后果,本站不承担任何责任。如需引用本文内容,请注明出处并尊重原作者的版权。
THE END
暂无评论内容