Search code examples
pythonwxpythoncpshutil

Copy Files From List Python


Im making a small python program to copy some files. My filenames are in a list "selectedList".

The user has selected the source dir "self.DirFilename" and the destination dir "self.DirDest".

I'm using cp instead of shutil because I've read that shutil is slow.

Heres my code:

for i in selectedList:
    src_dir = self.DirFilename + "/" + str(i) + ".mov"
    dst_dir = self.DirDest
    r = os.system('cp -fr %s %s' % (src_dir, dst_dir))
    if r != 0:
        print 'An error occurred!'**

I would like the copy to search the source directory for the given filename and then recreate the folder structure in the destination as well as copy the file.

Any suggestions would be helpful (like any massively obvious mistakes that i'm making)- its my first python programme and I'm nearly there!

Thanks Gavin


Solution

  • I think something like this could do the trick. Of course you may want to use something ore advance that os.system to call cp.

    import os
    
    for r, d, f in os.walk(self.DirFilename):
        for file in f:
            f_name, f_ext = os.path.splitext(file)
            if ".mov" == f_ext:
                if f_name in selectedList:
                    src_abs_path = os.path.join(r, file)
                    src_relative_path = os.path.relpath(src_abs_path, self.DirFilename)
                    dst_abs_path = os.path.join(self.DirDest, src_relative_path)
                    dst_dir = os.path.dirname(dst_abs_path)
                    if not os.path.exists(dst_dir):
                        os.makedirs(dst_dir)
                    ret = os.system('cp -fr %s %s' % (src_abs_path, dst_abs_path))
                    if ret != 0:
                        print 'An error occurred!'