开发者

Python 'No such file or directory' opening path `~/filename` with mode `w+`

I'm trying to open a file that doesn't exist with this line:

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

That should open it if it exists, and then wipe content to begin to write. If it doesn't exist, it should create it...right?

It doesn'开发者_运维知识库t. I get this error.

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

Ideas?


The ~ alias for the home directory is a shell-ism (something the shell does for you), not something you can use with the Python open command:

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>

>>> _


While it's true that Python's open does not support ~ expansion directly, you can use it in conjunction with the Python standard library function 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜