具有通配符支持的Python Windows文件复制 [英] Python Windows File Copy with Wildcard Support
问题描述
我一直在这样做:
result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y'])
if result == 0:
do_something()
else:
do_something_else()
直到今天,我开始研究pywin32模块,然后才看到诸如win32file.CopyFiles()之类的功能,但是后来我发现它可能不支持将文件复制到目录中.也许此功能隐藏在某个地方,但我还没有找到它.
Until today I started to look into pywin32 modules, then I saw functions like win32file.CopyFiles(), but then I found it may not support copying files to a directory. Maybe this functionality is hidden somewhere, but I haven't found it yet.
我也尝试过"glob"和"shutil"的组合,但是如果有很多文件,"glob"的运行速度会令人难以置信.
I've also tried "glob" and "shutil" combination, but "glob" is incredibly slow if there are many files.
那么,您如何使用Python模拟该Windows命令?
So, how do you emulate this Windows command with Python?
copy 123*.xml out_folder\. /y
推荐答案
以下代码提供了可移植的实现.
The following code provides a portable implementation.
请注意,我使用的是iglob(Python 2.5中已添加),它创建了一个生成器,因此它不会首先将整个文件列表加载到内存中(这就是glob的作用).
Note that I'm using iglob (added in Python 2.5) which creates a generator, so it does not load the entire list of files in memory first (which is what glob does).
from glob import iglob
from shutil import copy
from os.path import join
def copy_files(src_glob, dst_folder):
for fname in iglob(src_glob):
copy(fname, join(dst_folder, fname))
if __name__=='__main__':
copy_files("123*.xml", "out_folder")
其他文档:
- shutil.copy
- os.path.join
- glob.iglob
这篇关于具有通配符支持的Python Windows文件复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!