0

Okay so if I am going to make a Python application that will be distributed to others I need all the file paths to not be absolute, but relative to the root directory (I believe).

Let's say the file system looks something like this:

root
 |
 | - app.py
 | - data
 |    |
 |    | - file1.txt
 |    | - file2.txt
 |
 | - src
      |
      | - python_file.py

Of course the file system would be more complex than this. However, let's say I need the python_file.py to grab the file1.txt. How would you do this for an application that cannot use any absolute paths. I assume it is with the os module, I have seen some examples, but many of them are different, and some do not work.

I would love to know how to do this so that all the files can interact together correctly for any system ('dynamically' so to speak).

pjs
  • 18,696
  • 4
  • 27
  • 56
  • I believe there was something like `import ..data.file1` but I don't quite remember – lord_haffi Aug 24 '23 at 14:11
  • Please read tag descriptions before using a tag. The `distribution` tag doesn't mean what you think. – pjs Aug 24 '23 at 17:59
  • " I need all the file paths to not be absolute, but relative to the root directory (I believe)." I guess they just need to be all relative to *some* path in your project, not necessarily the root directory. – juanpa.arrivillaga Aug 24 '23 at 18:54

1 Answers1

2

I'll simplify your layout a bit and make it a single package (which could live in an src layout; you generally don't want an app.py outside an src layout):

  • justins_app/
    • __init__.py
    • __main__.py (this is run when you invoke python -m justins_app)
    • consts.py
    • data/
      • file1.txt
      • file2.txt

Now, consts.py could simply have

import pathlib

data_path = pathlib.Path(__file__).parent / "data"

to determine data/ from the __file__ magic global and you could then do e.g.

from justins_app.consts import data_path

file1_path = data_path / "file1.txt"
print(file1_path.read_text())

in another module.

Then, when you distribute this, you'd tell your packaging system to include the data directory in the package too (see e.g. here for Hatch's instructions for that).

AKX
  • 152,115
  • 15
  • 115
  • 172