Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Writing to files within packages?

Using this general structure:

setup.py
/package
    __init__.py
    project.py
    /data
        client.log

I have a script that saves a list of names to client.log, so I don't have to reinitialize that list each time I need access to it or run the module. Before I set up this structure with pkg_resources, I used open('.../data/client.log', 'w') to update the log with explicit paths, but this doesn't work anymore.

Is there any way to edit data files within modules? Or is there a better way to save this list?

like image 535
Insarov Avatar asked May 03 '13 19:05

Insarov


People also ask

How do you write data to a file in Python?

You can write to a file in Python using the open() function. You must specify either “w” or “a” as a parameter to write to a file. “w” overwrites the existing content of a file. “a” appends content to a file.

How do I include a file in a Python package?

Place the files that you want to include in the package directory (in our case, the data has to reside in the roman/ directory). Add the field include_package_data=True in setup.py. Add the field package_data={'': [... patterns for files you want to include, relative to package dir...]} in setup.py .


1 Answers

No, pkg_resources are for reading resources within a package. You can't use it to write log files, because it's the wrong place for log files. Your package directory should typically not be writeable by the user that loads the library. Also, your package may in fact be inside a ZIP-file.

You should instead store the logs in a log directory. Where to put that depends on a lot of things, the biggest issue is your operating system but also if it's system software or user software.

like image 165
Lennart Regebro Avatar answered Sep 21 '22 20:09

Lennart Regebro