2017-04-16 110 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())