我想将特定文件扩展名的文件复制到一个新文件夹中。我有使用
os.walk
的想法,但具体如何使用呢?我只想在一个文件夹中搜索具有特定文件扩展名的文件(该文件夹有2个子目录,但我不需要在这两个子目录中搜索找到这些文件)。谢谢。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())。
import os, shutil
for basename in os.listdir(srcdir):
if basename.endswith('.ext'):
pathname = os.path.join(srcdir, basename)
if os.path.isfile(pathname):
shutil.copy2(pathname, dstdir)
basename = os.path.normcase(basename)
在 basename.endswith
前面可能会很有用(在Windows上)。 - jfs以下是使用 os.walk
的非递归版本:
import fnmatch, os, shutil
def copyfiles(srcdir, dstdir, filepattern):
def failed(exc):
raise exc
for dirpath, dirs, files in os.walk(srcdir, topdown=True, onerror=failed):
for file in fnmatch.filter(files, filepattern):
shutil.copy2(os.path.join(dirpath, file), dstdir)
break # no recursion
例子:
copyfiles(".", "test", "*.ext")
这将遍历具有子目录的树。您可以进行os.path.isfile检查以使其更加安全。
for root, dirs, files in os.walk(srcDir):
for file in files:
if file[-4:].lower() == '.jpg':
shutil.copy(os.path.join(root, file), os.path.join(dest, file))
.lower()
是错误的(MS Windows占主导地位,但它并不是整个世界)。相比之下,推荐使用os.path.normcase(file)
。 - jfsimport os, shutil, sys
srcDir = sys.argv[1]
dstDir = sys.argv[2]
extension = sys.argv[3]
print "Source Dir: ", srcDir, "\n", "Destination Dir: ",dstDir, "\n", "Extension: ", extension
for root, dirs, files in os.walk(srcDir):
for file_ in files:
if file_.endswith(extension):
shutil.copy(os.path.join(root, file_), os.path.join(dstDir, file_))