Python Help

Discussion in 'Mac Programming' started by citizensmith, Nov 3, 2006.

  1. citizensmith macrumors newbie

    Joined:
    Sep 13, 2006
    #1
    Hi,

    I'm trying to learn Python. I'm working through a tutorial and I've hit a problem where I can't read anything from files. I get an error message saying no file or directory exists.

    Heres my code:

    # the open function returns a file object
    file = open('Users/jamie/Python/German.txt', 'rb')

    # loop over each line of the file
    for line in file:
    print line

    # releases the file object

    file.close()


    Any help would be great!

    Thanks
     
  2. iMeowbot macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #2
    This line:
    Code:
    file = open('Users/jamie/Python/German.txt', 'rb')
    needs a leading slash to be a full path:
    Code:
    file = open('/Users/jamie/Python/German.txt', 'rb')
    Without the leading slash, it's trying to find all that beneath your current working directory.
     
  3. citizensmith thread starter macrumors newbie

    Joined:
    Sep 13, 2006
    #3
    Ah great thanks!

    I've only just switched to Mac so I'm still getting to grips with the file system.

    Sorry for the uber noob question!
     
  4. iMeowbot macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #4
    Yep, it's all obvious, after you know :D

    You can use os.path.realpath to get a better feel for how these things happen. Try these from the Python interactive prompt:

    Code:
    import os
    print os.path.realpath('German.txt')
    print os.path.realpath('Users/jamie/Python/German.txt')
    print os.path.realpath('/Users/jamie/Python/German.txt')
    
     
  5. citizensmith thread starter macrumors newbie

    Joined:
    Sep 13, 2006
    #5
    Thats cool, so could I have written my code like this?

    import os
    file = open(os.path.realpath('German.txt'))
     
  6. iMeowbot macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #6
    If the file is on your working directory, you don't even need that much.

    file = open('German.txt')

    would be enough. The realpath stuff is just so you can see what Python is doing behind the scenes.
     
  7. citizensmith thread starter macrumors newbie

    Joined:
    Sep 13, 2006
    #7
    Ah right good stuff. I like the very little of this language I've played with. Much cleaner than Java.
     

Share This Page