Leonel
Leonel

Reputation: 29189

How to access templates in Python?

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 ?

Upvotes: 2

Views: 286

Answers (2)

Hans Nowak
Hans Nowak

Reputation: 7897

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

Upvotes: 1

Daniel Naab
Daniel Naab

Reputation: 23056

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.

Upvotes: 2

Related Questions