Search code examples
pythonerror-handlingioerror

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?


Solution

  • 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>
    
    >>> _