Python Windows File Copy with Wildcard Support

Wang Dingwei picture Wang Dingwei · Apr 6, 2010 · Viewed 10.4k times · Source

I've been doing this all the time:

result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y'])
if result == 0: 
    do_something()
else:
    do_something_else()

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.

I've also tried "glob" and "shutil" combination, but "glob" is incredibly slow if there are many files.

So, how do you emulate this Windows command with Python?

copy 123*.xml out_folder\. /y

Answer

Frederik picture Frederik · Apr 6, 2010

The following code provides a portable implementation.

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")

Additional documentation: