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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.