2017-04-16 108 views
1

爲什麼下面的交互失敗? (蟒蛇3.6.1)Python無法寫入文件引用'FileNotFoundError'

>>> with open('an_image.png', 'rb') as f, open('~/Desktop/an_image.png', 'wb') as g: 
...  g.write(f.read()) 
... 
Traceback (most recent call last): File "<stdin>", line 1, in 
<module> FileNotFoundError: [Errno 2] No such file or directory: 
'~/Desktop/an_image.png' 
>>> 

是不是「W」模式,應該創建該文件,如果它不存在?

+1

嗯,跟蹤回不匹配的代碼片段(提示rei_G_01.png不符an_image.png - 有時編輯爲簡潔,當我解決我的代碼...或者添加錯誤;-)但是,我猜在這種情況下,代字號可能未被展開,因此找不到文件夾放置文件,對嗎? – Dilettant

+1

@Dilettant:不,這是我的錯。我在寫這篇文章時手動更改了文件名,但沒有做一個徹底的工作... –

+1

沒問題,檢查代字號擴展......也許去'os.path.expanduser(路徑)' – Dilettant

回答

3

正如Dilettant所說,刪除~。你可以手動指定的絕對路徑,或使用os.path.expanduser

import os 

desktop_img = os.path.expanduser('~/Desktop/an_image.png') 
# desktop_img will now be /home/username/Desktop/an_image.png 

with open('an_image.png', 'rb') as f, open(desktop_img, 'wb') as g: 
    g.write(f.read())