views:

88

answers:

2

Sometimes, for a program with a lot of data, it is common to place the data in an external file. An example is a script that produces an HTML report, using an external file to hold a template.

In Java, the most recommended way to retrieve a resource of the program is to use getClass().getClassLoader().getResource() or getClass().getClassLoader().getResourceAsStream() for a stream.

The advantage is that this is independent of the file system. Also, it works whether the classes are in the file system or the application is distributed as a Jar file.

How do you achieve the same in Python ? What if you're using py2exe or Freeze to generate a stand-alone running app, as seen in this question ?

+2  A: 

You can use os.path.dirname(__file__) to get the directory of the current module. Then use the path manipulation functions (specifically, os.path.join) and file input/output to open a file under the current module.

Daniel
+1  A: 

What Daniel said. :-) Also, py2exe can be told to include external files (this is often used for images etc).

Hans Nowak