为什么以下互动失败? (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;模式应该创建文件,如果它不存在?
答案 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())