【问题标题】:open() is not working for hidden files pythonopen() 不适用于隐藏文件 python
【发布时间】:2013-07-04 01:50:04
【问题描述】:

我想使用 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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多