2013-11-03 37 views
0

文件試圖保存Python文件:無法保存在python

g = open('~/ccna_pages/'+filename, 'w') 
g.write(page) 
g.close() 

得到這個錯誤:

Traceback (most recent call last): File "dl-pages.py", line 50, in g = open('~/ccna_pages/'+filename, 'w') IOError: [Errno 2] No such file or directory: '~/ccna_pages/1.0.1.1.html'

但是,目錄不會在該位置存在。

此語法似乎是什麼Python文檔建議.. http://docs.python.org/release/1.5/tut/node46.html

我缺少什麼?謝謝..

+0

作爲調試方法,儘量只寫一個文件沒有文件路徑,只是一個名稱,以確保那不是問題 –

+8

你可能不想閱讀Python 1.5文檔。 – geoffspear

回答

6

Python不會爲您擴展~,您需要手工完成。

例子:

>>> with open('~/test', 'w') as f: 
...  pass 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IOError: [Errno 2] No such file or directory: '~/test' 
>>> with open('/home/mihai/test', 'w') as f: 
...  pass 
... 
+2

爲什麼downvote?請告訴我我錯在哪裏 –

+2

從我那裏得到+1。 -1可能是從考慮問題太小的人來回答,它會發生 – alko

2

os.path模塊,滿載而歸,包括expanduser

import os 

filename = 'whatever.txt' 
dir = '~/ccna_pages/' 

if dir.startswith('~'): 
    dir = os.path.expanduser(dir) 

path = os.path.join(dir, filename) 
print(path) # /home/some1/ccna_pages/whatever.txt