Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

citizensmith

macrumors newbie
Original poster
Sep 13, 2006
6
0
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
 

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
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.
 

citizensmith

macrumors newbie
Original poster
Sep 13, 2006
6
0
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!
 

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
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')
 

citizensmith

macrumors newbie
Original poster
Sep 13, 2006
6
0
Thats cool, so could I have written my code like this?

import os
file = open(os.path.realpath('German.txt'))
 

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
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.
 

citizensmith

macrumors newbie
Original poster
Sep 13, 2006
6
0
Ah right good stuff. I like the very little of this language I've played with. Much cleaner than Java.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.