0

So I have the directory struture like this

  Execute_directory--> execute.py
  |
  Algorithm ---> algorithm.py
            |
            |--> data.txt

So I am inside execute directory and have included the following path to my python path.

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../Algorithm")

algorithm.py has a code to read data.txt

So when I run execute.py , execute.py calls algorithm.py which in turns read data.txt I thought that above line should have done the job. it is able to find algorithm.py but not data.txt??

         IOError: [Errno 2] No such file or directory:'data.txt'

Any clue what I am doing wrong ?? Thanks

frazman
  • 32,081
  • 75
  • 184
  • 269

3 Answers3

2

Are you reading data.txt in algorithm.py like this:

open('data.txt')

Because that is relative to the working directory and not relative to the scripts directory.

In algorithm.py you could try this:

open(os.path.join(os.path.dirname(__file__), 'data.txt'))
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
2

This would usually be an issue with relative filenames not being relative to where you expect. Print the contents of os.path.abspath(filename) to check this. If it gives you something strange, specifying the absolute path in the first place (when you initialise filename) should fix it.

lvc
  • 34,233
  • 10
  • 73
  • 98
  • 1
    +1 this is excellent advice, as it teaches OP how to go about *solving* this problem next time it crops up as well as hints at how to solve similar problems too. – Daren Thomas Apr 13 '12 at 07:55
1

sys.path is used to tell Python where to look for modules when you use import. It does not affect looking for files with open. When you open a file, relative paths are relative to the "current working directory", which you can check with os.getcwd and change with os.chdir.

Bonus: if you check the value of sys.path at startup, you will see that it includes ''. This tells Python to also check the current working directory for modules (as well as the hard-coded absolute paths in sys.path, which is why, if you start a Python interpreter while "in" (using a command prompt) the folder that contains your module, you don't have to tell it where to look for your module.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153