Question

So I have been building a text based game in python as a project for learning python, implementing things as I learn them, so I started getting this error in some cases, I have been developing this game on a raspberry pi, on a machine running mint 13 and on an android tablet. Lately though I rebuilt the game in python 3.3, when I did that I started getting an error when I go to open from a directory path the code is this

 with open('rooms/' + str(id) + '.json', 'r', ) as f:
     jsontext = f.read()

I store my rooms as json files in a separate folder in the same directory that the project lies in if any one would like to see how this works you can check out the project over at www.github.com/kevin2314/TextGame. On both my raspberry pi and on my mint 13 machine this code works just fine but on my android tablet, it returns an error like this

 IOError: [Errno 2] No such file or directory: "rooms/intro.json"

At first I thought this might have just been because it was on android and it's not specifically built for programming in python so I didn't pay much attention to it. After I released it to github though, another person had the same issue except they were using Ubuntu, So I'm at a loss as to what the issue is with the path.

If any one can shed some light on this I'd be grateful I wouldn't like to start having this problem with a lot of people

Was it helpful?

Solution

The path that you are referring to is dependent on the starting directory. You should use the __file__ global variable:

with open(os.path.join(
             os.path.dirname(__file__), 'rooms', + str(id) + '.json'),
          'r') as f:
    jsontext = f.read()

I would also suggestion using os.path.join to create the file name so that you can use the platform specific path separators.

Note that os.curdir() will return the location from which the program was started, not the location of the rooms.py file.

OTHER TIPS

You could use os.getcwd() to find your current directory and continue from there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top