我正在尝试打开一个不存在以下代码行的文件:
x = open("~/tweetly/auth", 'w+')这应该会打开它,如果它存在,然后擦除内容开始写入。如果它不存在,它应该创建it...right?
不是的,我得到了这个错误。
IOError: [Errno 2] No such file or directory: '~/tweetly/auth'想法?
发布于 2011-10-11 12:24:47
主目录的外壳别名是~ -ism(外壳为您执行的操作),而不是您可以与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>
>>> _发布于 2011-10-11 12:42:52
虽然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>https://stackoverflow.com/questions/7721345
复制相似问题