Python无法写入文件引用' FileNotFoundError'

时间:2017-04-16 07:57:58

标签: python python-3.x file

为什么以下互动失败? (python 3.6.1)

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

不是&#39; w&#39;模式应该创建文件,如果它不存在?

1 个答案:

答案 0 :(得分: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())