2013-04-29 49 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