1

我正在尝试打开此行不存在的文件:

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

如果它存在,它应该打开它,然后擦除内容以开始写入。如果它不存在,它应该创建它......对吗?

它没有。我得到这个错误。

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

想法?

4

2 回答 2

4

主目录的~别名是 shell-ism(shell 为你做的事情),而不是你可以与 Pythonopen命令一起使用的东西:

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>

>>> _
于 2011-10-11T04:24:47.293 回答
4

虽然 Pythonopen确实不支持~直接扩展,但您可以将它与 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>
于 2011-10-11T04:42:51.940 回答