Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Windows File Copy with Wildcard Support

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
like image 554
Wang Dingwei Avatar asked Apr 06 '10 11:04

Wang Dingwei


1 Answers

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:

  • shutil.copy
  • os.path.join
  • glob.iglob
like image 109
Frederik Avatar answered Sep 24 '22 10:09

Frederik