0

I've created an executable Python file through py2exe.

If I run this executable in its dist folder, it runs just fine.

This program it needs to have access to files that are in the dist folder (txt files with reference data).

If I create a shortcut in my desktop to that executable file, the program runs but doesn't work properly. It seems that the program runs as its folder was the folder where the shortcut is, not where the exe is. So, it cannot find these txt files with the reference data.

In my code, I call those txt files like this:

ref_correction = np.matrix(np.genfromtxt( 'Reference_Data.txt' ))

How can I fix this?

Abdur Rahman
  • 657
  • 16
  • 46
cinico
  • 268
  • 6
  • 15

2 Answers2

1

You can construct the path to your data files by using the __file__ variable (which contains the path to the Python file you're currently writing code in). You can extend that to be an absolute path (by using os.path.abspath()), then take just the directory part of that path, and join it with the name of your data file.

djc
  • 11,603
  • 5
  • 41
  • 54
  • Thanks! Sorry for the newbie question :) – cinico Feb 25 '13 at 11:01
  • Actually, now I'm having a different error when running the executable (NameError: global name '__file__' is not defined) Before turn it into a exe with py2exe, I don't have that problem. – cinico Feb 25 '13 at 14:48
  • I think I cannot use the __file__ for an exe file. I did't understand very well, but that's what I think from this thread: http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python – cinico Feb 25 '13 at 14:55
0

Use this instead:

path = os.getcwd()   #Where the 'exe' file is stored 

otherpath = os.path.join(path, '../Folder/SubFolder/') #Creates a new path

When creating an '.exe' file the "__ file __" no longer applies to the path, so you need to get the current working directory with the line above. This will update your path to the directory that the '.exe' and all the required files are currently in.