Python打开路径`~/filename`时出现'没有那个文件或目录'错误,模式为`w+`

1 投票
2 回答
1727 浏览
提问于 2025-04-17 04:04

我正在尝试用这一行代码打开一个不存在的文件:

x = open("~/tweetly/auth", 'w+')

如果文件存在的话,这行代码应该能打开它,然后清空内容以便开始写入。如果文件不存在,它应该创建一个新的...对吧?

但实际上并没有这样做。我收到了这个错误。

IOError: [Errno 2] No such file or directory: '~/tweetly/auth'

有什么想法吗?

2 个回答

4

虽然Python的open函数不直接支持~这个符号的扩展,但你可以结合使用Python标准库中的一个函数os.path.expanduser来实现这个功能:

>>> import os
>>> os.path.expanduser("~/qq.s")
'/Users/nad/qq.s'
>>> open(os.path.expanduser("~/qq.s"), 'w+')
<open file '/Users/nad/qq.s', mode 'w+' at 0x1049ef810>
4

在这里,~ 这个符号代表的是你的主目录,这是一个在命令行中常用的写法,叫做“shell 习惯用法”。但是,当你在 Python 中使用 open 命令时,这个符号就不能直接用。

pax:~$ cd ~

pax:~$ ls qq.s
qq.s

pax:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> open("~/qq.s")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '~/qq.s'

>>> open("./qq.s")
<open file './qq.s', mode 'r' at 0xb7359e38>

>>> _

撰写回答