简体   繁体   中英

How can a Python module access data files located in another directory (project and built package)?

In my Python project I am reading from a file in another directory. This works fine in the default project but when I build the project the config file integration is messy.

This is the project directory :

.
+--config
|  +-- config.json 
+--src
|   +--filereader
|       +-- filereader.py
|       +--__init__.py
+--pyproject.toml
+--setup.cfg

I managed to get the config file into the built project by adding following lines to the setup.cfg file.

[options.data_files]
filenameparser = config/filenameparser/config.json

The config.json is written to the data subdirectory. This is the directory tree of the build project (running in a virtual environment):

.
+--venv
|    +--data
|       +-- config.json 
|     +--Lib
|        +--site-packages
|           +-- filereader
|               +--filereader.py
|               +--__init__.py

How can filereder.py access the config file in the default project as well as in the built project and what is the "clean" way?

If i have understood your question correcty, your are asking how to get data from a file in another directory or ina sub directory in your "filereder.py"s directory.

The cleanest way is to specify the path.

You can do this my eider copy-pasting the the file path or by using OS module :

dir_path= os.path.dirname(os.path.realpath(__file__)) #to take File path

and if you want to access sub-directory then:

dir_path= os.path.dirname(os.path.realpath(__file__)) #to take File path
final_dir= f"{dir_path}\\Your_sub-directory_name"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM