2013-07-04 19 views
5

Tôi muốn tạo và viết tệp .txt trong một thư mục ẩn bằng cách sử dụng python. Tôi đang sử dụng mã này:open() không hoạt động đối với các tệp bị ẩn python

file_name="hi.txt" 
temp_path = '~/.myfolder/docs/' + file_name 
file = open(temp_path, 'w') 
file.write('editing the file') 
file.close() 
print 'Execution completed.' 

nơi ~/.myfolder/docs/là một thư mục ẩn. Tôi nhận được lỗi:

Traceback (most recent call last): 
    File "test.py", line 3, in <module> 
    file = open(temp_path, 'w') 
IOError: [Errno 2] No such file or directory: '~/.myfolder/docs/hi.txt' 

Cùng một mã hoạt động khi tôi lưu tệp vào một số thư mục không ẩn.

Bất kỳ ý tưởng nào tại sao open() không hoạt động đối với các thư mục ẩn.

+0

Bạn đang sử dụng hệ điều hành nào? – enginefree

+0

http://stackoverflow.com/questions/13215716/ioerror-errno-13-permission-denied-when-trying-to-open-hidden-file-in-w-mod – John

+0

Tôi đang sử dụng ubuntu – user2460869

Trả lời

11

Vấn đề không phải là nó bị ẩn, đó là Python không thể giải quyết việc bạn sử dụng ~ đại diện cho thư mục chính của bạn. Sử dụng os.path.expanduser,

>>> with open('~/.FDSA', 'w') as f: 
...  f.write('hi') 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IOError: [Errno 2] No such file or directory: '~/.FDSA' 
>>> 
>>> import os 
>>> with open(os.path.expanduser('~/.FDSA'), 'w') as f: 
...  f.write('hi') 
... 
>>> 
+0

nó hoạt động nhờ – user2460869

Các vấn đề liên quan