geek
geek

Reputation: 359

Absolute Path and Relative Path issue in python

How to remove path related problems in python?

For e.g. I have a module test.py inside a directory TEST

**test.py**
import os
file_path = os.getcwd() + '/../abc.txt'

f = open(file_path)
lines = f.readlines()
f.close

print lines

Now, when I execute the above program outside TEST directory, it gives me error:-

Traceback (most recent call last):
  File "TEST/test.py", line 4, in ?
    f = open(file_path)
IOError: [Errno 2] No such file or directory: 'abc.txt'

how to resolve this kind of problem. Basically this is just a small example that I have given up.

I am dealing with a huge problem of this kind.

I am using existing packages, which needs to be run only from that directory where it exists, how to resolve such kind of problems, so that I can run the program from anywhere I want.

Or able to deal with the above example either running inside TEST directory or outside TEST directory.

Any help.?

Upvotes: 0

Views: 2153

Answers (2)

Epcylon
Epcylon

Reputation: 4737

Your code is looking at the current working directory, and uses that as a basis for finding the files it needs. This is almost never a good idea, as you are now finding out.

The solution mentioned in the answer by Emil Vikström is a quickfix solution, but a more correct solution would be to not use current working directory as a startingpoint.

As mentioned in the other answer, __file__ isn't available in the interpreter, but it's an excellent solution for your code.

Rewrite your second line to something like this:

file_path = os.path.join(os.path.dirname(__file__), "..", "abc.txt")

This will take the directory the current file is in, join it first with .. and then with abc.txt, to create the path you want.

You should fix similar usage of os.getcwd() elsewhere in your code in the same way.

Upvotes: 0

Emil Vikström
Emil Vikström

Reputation: 91983

I think the easiest thing is to change the current working directory to the one of the script file:

import os
os.chdir(os.path.dirname(__file__))

This may cause problems, however, if the script is also working with files in the original working directory.

Upvotes: 3

Related Questions