Question

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

Était-ce utile?

La 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!'

Autres conseils

See http://blogs.blumetech.com/blumetechs-tech-blog/2011/05/faster-python-file-copy.html for a pure Python implementation of the recursive copy.

You can use os.walk to find the file you need:

def find_files(...):
    for ... in os.walk(...):
        if ...:
            yield filename

for name in find_files(...):
   copy(name, ...)
import glob
for fname in selectedList:
    filename = str(fname) + '.mov'
    found = glob.glob(os.path.join(self.DirFilename, filename))
    found.extend(glob.glob(os.path.join(self.DirFilename, '**', filename)))
    found = [(p, os.path.join(self.DirDest, os.path.relpath(p, self.DirFilename))) for p in found]
    for found_file in found:
        # copy files however
        #r = os.system('cp -fr %s %s' % found_file)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top