Python中的open()无法打开隐藏文件

9
我希望使用 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()不起作用。


你使用的是哪个操作系统? - user1786283
https://dev59.com/PmYs5IYBdhLWcg3wAfPO - John
它确实适用于隐藏文件。 - sasha sami
1个回答

20

问题不在于它被隐藏了,而是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')
... 
>>>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接