Results 1 to 2 of 2

Thread: python i/o errno2

  1. #1
    Join Date
    Jan 2008
    Beans
    13

    python i/o errno2

    Code:
    >>> f = open("~/myPy/test.txt", "r")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IOError: [Errno 2] No such file or directory: '~/myPy/test.txt'
    Why am I getting this error message? I have been running Python scripts successfully for several weeks, no problems. This is the first script I am beginning to write to open a file and do some work on it.

    I have searched for an answer without success. I have tried
    Code:
    peter@pubuntu:~$ export PYTHONPATH=$PYTHONPATH:~/myPy
    and this is my PYTHONPATH:
    Code:
    >>> import sys
    >>> from pprint import pprint as pp
    >>> pp(sys.path)
    ['',
     '/home/peter',
     '/home/peter/myPy',
     '/usr/lib/python25.zip',
     '/usr/lib/python2.5',
     '/usr/lib/python2.5/plat-linux2',
     '/usr/lib/python2.5/lib-tk',
     '/usr/lib/python2.5/lib-dynload',
     '/usr/local/lib/python2.5/site-packages',
     '/usr/lib/python2.5/site-packages',
     '/usr/lib/python2.5/site-packages/Numeric',
     '/usr/lib/python2.5/site-packages/PIL',
     '/usr/lib/python2.5/site-packages/gst-0.10',
     '/var/lib/python-support/python2.5',
     '/usr/lib/python2.5/site-packages/gtk-2.0',
     '/var/lib/python-support/python2.5/gtk-2.0']

  2. #2
    Join Date
    Dec 2009
    Beans
    18

    Re: python i/o errno2

    Quote Originally Posted by pmiln099 View Post
    Code:
    >>> f = open("~/myPy/test.txt", "r")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IOError: [Errno 2] No such file or directory: '~/myPy/test.txt'
    Why am I getting this error message?
    Obviously, because there is no such file or directory
    Tilda expansion is a shell feature and there is no surprise that library functions interpret '~' as a direcory name. You need the os.path.expanduser function. So your code should look like
    Code:
    import os
    f = open(os.path.expanduser("~/myPy/test.txt"), "r")

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •