如何在我的Python脚本(版本2.5)中将特定文件扩展名的文件复制到文件夹中?

23
我想将特定文件扩展名的文件复制到一个新文件夹中。我有使用 os.walk 的想法,但具体如何使用呢?我只想在一个文件夹中搜索具有特定文件扩展名的文件(该文件夹有2个子目录,但我不需要在这两个子目录中搜索找到这些文件)。谢谢。
5个回答

41
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())。


有没有不需要循环遍历每个文件就能完成的方法?如果我有18,000个文件,这将需要很长时间,能否并行处理? - Sauron

8
如果您不需要递归,就不需要使用walk()函数。
Federico的glob答案很好,假设您不会有任何名为“something.ext”的目录。否则,请尝试:
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)

1
basename = os.path.normcase(basename)basename.endswith 前面可能会很有用(在Windows上)。 - jfs

4

以下是使用 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")

3

这将遍历具有子目录的树。您可以进行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) - jfs

1
从srcDir复制扩展名为"extension"的文件到dstDir...
import 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_))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接