2012-10-06 32 views
0

我想複製我的Automater工作流程,我已將它們列在配置文件中,並且我想循環訪問配置文件並複製目錄。他們的名字中有空格,我遇到了麻煩。我在複製目錄時遇到了問題

它正確等打印的文件名,但複製失敗,因爲似乎是多餘的「」周圍的名稱與副本

import os 
import shutil 

confdir=os.getenv("my_config") 
dropbox=os.getenv("dropbox") 
conffile = ('services.conf') 
conffilename=os.path.join(confdir, conffile)  
sourcedir= (r'~/Library/Services/') 
destdir=os.path.join(dropbox, "My_backups") 

for file_name in open(conffilename): 
    sourcefile=os.path.join(sourcedir, repr(file_name.strip())) 
    print sourcefile 
    destfile=os.path.join(destdir, file_name.strip()) 
    shutil.copytree(sourcefile, destfile) 

和錯誤是提前

~/Library/Services/'Add PDF Metadata.workflow' 
Traceback (most recent call last): 
    File "Untitled 3.py", line 15, in <module> 
    shutil.copytree(sourcefile, destfile) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py",  line 168, in copytree 
    names = os.listdir(src) 
OSError: [Errno 2] No such file or directory: "~/Library/Services/'Add PDF Metadata.workflow'" 

謝謝

我已經嘗試了下面的建議,但它仍然不起作用

+0

我設法解決這一切在這裏 http://stackoverflow.com/questions/13052341/i-seem-to-get-an-error-although-the-script-runs-i-cant-看到爲什麼 – geekcomputers

回答

0

它不喜歡〜我把完整的路徑。我還剛剛編輯了一個位,並使用sourcedir = os.path.expanduser('〜/ Library/Services /')來展開主目錄

1

爲什麼在file_name.strip()上使用repr()?這將圍繞你的文件名用單引號 - 而這些都不存在於文件路徑。刪除repr(),它應該工作。

+0

感謝您的回覆。由於名稱中有空格,因此我在文件名上使用了repr()。我試過沒有repr(),我仍然得到相同的錯誤 – geekcomputers

+0

你確定該錯誤信息中的文件存在於源目錄中? –

+0

是Macintosh-3:配置craigdba $ ls -l〜/ Library/Services/ total 0 drwxr-xr-x @ 3 craigdba craigdba 102 1月17日17:25添加PDF Metadata.workflow drwxr-xr-x @ 3 craigdba craigdba 102 1月17日17:17添加Spotlight評論。工作流 drwxr-xr-x 3 craigdba admin 102 20 Nov 2007 NoteBookHelper.service – geekcomputers

0

shutil.copytree(src, dst)將以遞歸方式將位於src的目錄樹(及其中的所有文件)複製到位於dst的新目錄樹。它並不意味着與文件一起使用。

在這裏,你想複製單個文件,而不是一個完整的目錄樹,你應該只使用shutil.copyshutil.copy2

如果這些文件可能位於您要複製一個目錄樹,那麼你可以調用shutil.copy(sourcefile)實際文件拷貝到destfile之前使用os.makedirsos.path.dirname(destfile)返回的路徑。

但是,請注意,調用os.makedirs時,如果目標已存在,將會引發錯誤,因此您可能需要try/except

+0

這是一個我想複製的目錄 – geekcomputers

+0

@geekcomputers哦,你說得對, 「〜/ Library/Services /'添加PDF Metadata.workflow'」'讓我感到困惑。你現在可以發佈新的錯誤消息,你已經刪除了'repr()'調用嗎? –

+0

OSError:[Errno 2]沒有這樣的文件或目錄:'〜/ Library/Services/Add PDF Metadata.workflow' – geekcomputers