我想将具有特定文件扩展名的文件复制到新文件夹.我知道如何使用os.walk
但具体如何使用它?我只在一个文件夹中搜索具有特定文件扩展名的文件(此文件夹有2个子目录,但我在寻找的文件永远不会在这两个子目录中找到,所以我不需要在这些子目录中搜索) .提前致谢.
Fed*_*oni 32
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)
Run Code Online (Sandbox Code Playgroud)
阅读shutil模块的文档,选择适合您需求的函数(shutil.copy(),shutil.copy2()或shutil.copyfile()).
如果您没有递归,则不需要walk().
假设你不会有任何名为'something.ext'的目录,Federico对glob的回答很好.否则尝试:
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)
Run Code Online (Sandbox Code Playgroud)
这是一个非递归版本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
Run Code Online (Sandbox Code Playgroud)
例子:
copyfiles(".", "test", "*.ext")
Run Code Online (Sandbox Code Playgroud)