1

I'd like to load an CSV file from another package.

In my case I want to call csv.reader in the reader.py and load / open there the Pers1_fb.csv from the data package.

My intention is to use the data package as ressource folder, similar to Java

How can I archieve this? I am on Python 3.9

My folder structure is like this:

- Project_Folder
   |
   |- main
        |- __init__.py
        |- reader.py
    

   |- data
        |- __init__.py
        |- Pers1_fb.csv
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Does this answer your question? [Managing resources in a Python project](https://stackoverflow.com/questions/1395593/managing-resources-in-a-python-project) – Tomerikoo Nov 08 '21 at 18:44
  • not really because it features a deprecated way of achieving this, I guess – cdr_chakotay Nov 08 '21 at 19:20

2 Answers2

3

You can determine the path to the data folder as one relative to the built-in __file__ attribute (which is the path to the currently executing script/module .py file). This can easily be done with the pathlib module:

Code in reader.py:

from pathlib import Path

data_folder_path = (Path(__file__) / '../../data' ).resolve()
csv_file_path = data_folder_path / 'Pers1_fb.csv'
print(csv_file_path)  # -> 'Project_Folder/data/Pers1_fb.csv'
martineau
  • 119,623
  • 25
  • 170
  • 301
0

I'd say just get the current directoy, go up one file level and then navigate as usual from there. Using the os for example:

base = os.path.dirname(os.getcwd())
data_path = os.path.join(base, 'data')

I'm sure that this can be done more elegantly with Pathlib too!

Puff
  • 503
  • 1
  • 4
  • 14
  • 2
    Using the current directory is unreliable because it often isn't the same as the script being executed, depending on how it was run. – martineau Nov 08 '21 at 18:36
  • I was assuming the exact file structure posted in the question, but I see your point. – Puff Nov 08 '21 at 18:43
  • 1
    The file structure isn't that relevant to the point I was trying to make. I meant for example that the script could have been executed from some arbitrary folder simply by specifying a full path to it: i.e. via `python Project_Folder/main/reader.py` without changing the current directory. – martineau Nov 08 '21 at 18:59