如何将具有特定文件扩展名的文件复制到我的 python(2.5 版)脚本中的文件夹中?
问题描述
我想将具有特定文件扩展名的文件复制到新文件夹.我知道如何使用 os.walk
但具体来说我将如何使用它?我只在一个文件夹中搜索具有特定文件扩展名的文件(此文件夹有 2 个子目录,但我要查找的文件永远不会在这 2 个子目录中找到,因此我不需要在这些子目录中搜索).提前致谢.
I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use os.walk
but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.
解决方案
import glob, os, shutil
files = glob.iglob(os.path.join(source_dir, "*.ext"))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, dest_dir)
阅读shutil模块的文档选择适合您需要的函数(shutil.copy()、shutil.copy2() 或 shutil.copyfile()).
Read the documentation of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()).
相关文章