2013-04-29 53 views
0

我正在制作一个小型的Python程序来复制一些文件。我的文件名在“selectedList”列表中。从列表中复制文件Python

用户已选择源目录“self.DirFilename”和目标目录“self.DirDest”。

我使用cp而不是shutil,因为我读过shutil很慢。

继承人我的代码:

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

我想复制到搜索源目录中所给的文件,然后重新创建在目标文件夹结构以及复制文件。

任何建议都会有帮助(就像我正在做的任何大量明显的错误) - 它是我的第一个Python程序,我快到了!

感谢 加文

+1

为了避免具有有趣的非转义字符问题和安全问题(如空白),这样做:'R = subprocess.call(( 'CP', '-fr',src_dir,dst_dir + '/' ))' – pts 2013-04-29 20:41:57

+0

仅供参考'shutil'由于其缓冲区大小仅为16K而复制速度慢。根据多个来源(如http://blogs.blumetech.com/blumetechs-tech-blog/2011/05/faster-python-file-copy.html),较大的缓冲区大小可能会产生很大的差异。对于递归副本,更改'shutil'缓冲区大小并不容易。请参阅上面的链接以获取可能的实现可能的巨大差异与不同的磁盘搜索模式有关。 – pts 2013-04-29 20:46:09

+0

这对我来说不是什么问题。 – pts 2013-04-29 20:48:51

回答

0

我觉得这样的事情可以做的伎俩。当然你可能想使用os.system调用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!' 
+0

谢谢祖金,这工作,但只为列表中的第一项。你的代码对我来说有点高级,我会花一些时间来弄明白。谢谢你的帮助。 – 2013-04-29 21:32:35

+0

了解你的代码后,我发现它有一个问题。它适用于我,但复制1个文件后卡住了。我得到这个错误: – 2013-04-30 14:10:04

+0

Traceback(最近一次调用最后): 文件“/Users/gavinhinfey/Desktop/ALEXAFROMEDL.py”,行119,在DoTheCopy src_abs_path = os.path.join(r,文件) 文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py”,第77行,加入 elif path ==''或path.endswith('/'): AttributeError :'int'对象没有属性'endswith' – 2013-04-30 14:10:31

0
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) 
+0

found = [(p,os.path.join(self.DirDest,os.path.relpath(p,self.DirFilename)))for p in found] ^ SyntaxError:invalid syntax – 2013-04-29 21:01:24

+0

感谢帮助 – 2013-04-29 21:01:53

+0

@GavinHinfey奇怪,我没有得到一个语法错误。它抱怨什么? – cmd 2013-04-29 21:06:42