老布接到一个小任务,有一批.txt文件,需要根据特定关键词选出包含关键词的.txt文件并移动到新的文件夹。虽然市面上有软件工具可以实现这个需求。不过为了这个需求就到处测试软件工具显然太浪费时间,于是搬出我们的python,使用python编写一个根据关键词移动.txt文件的脚本工具显然更具有性价比。
啥也不说了,上代码:
根据关键词移动.txt文件python脚本代码
import os import shutil def move_files_with_keyword(source_folder, destination_folder, keyword): if not os.path.exists(destination_folder): os.makedirs(destination_folder) for file_name in os.listdir(source_folder): if file_name.endswith('.txt') and keyword in file_name: source_path = os.path.join(source_folder, file_name) destination_path = os.path.join(destination_folder, file_name) shutil.move(source_path, destination_path) print(f"已经移动 {file_name} 到 {destination_folder}") if __name__ == "__main__": source_folder = input("请输入源文件夹路径:") destination_folder = input("请输入目标文件夹路径:") keyword = "硕士" move_files_with_keyword(source_folder, destination_folder, keyword)
使用说明:
根据自己需求修改代码中
keyword = "硕士"
的关键词。比如,把这里的“硕士”修改为你需要的“博士”。
然后运行代码(老布是在PyCharm中直接运行的)即可。
输入原文件夹路径和需要保存到的文件夹路径即可。
不得不说python运行速度还是非常快的,老布测试60万个.txt文件筛选一次仅需10分钟。当然这可能和你电脑配置性能有关。