[英]the For loop inside open files is not working on open files in Python
[英]open() is not working for hidden files python
我想使用python在隱藏文件夾中創建和編寫.txt文件。 我正在使用此代碼:
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.'
其中〜/ .myfolder / docs /是一個隱藏文件夾。 我收到錯誤:
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'
當我將文件保存在某個非隱藏文件夾中時,相同的代碼可以正常工作。
任何想法為什么open()不適用於隱藏文件夾。
問題不在於它是隱藏的,而是Python無法解決你對~
表示主目錄的使用。 使用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')
...
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.