Mr.cysl
Mr.cysl

Reputation: 1614

How to read files from subdir when creating python package

I am trying to package my code and I have a structure like

proj
|---- __init__.py
|---- main.py
|---- data
       |---- file_to_read.csv

And I am trying to use path ./data/file_to_read.csv in main.py. However, that is not working as I got errors like FileNotFoundError: [Errno 2] No such file or directory:. What should I do then?

Upvotes: 2

Views: 294

Answers (2)

user9074332
user9074332

Reputation: 2636

Please give the nice pathlib library a try.

├── __init__.py
├── data
│   └── file_to_read.csv
└── main.py

data/file_to_read.csv

a,b
c,d

main.py

import pathlib

file_path = pathlib.Path(__file__).parents[0].absolute()
data_path = file_path / 'data/file_to_read.csv'

with open(str(data_path)) as data_file:
    data = data_file.read().rstrip()

print(data)

run it

$ python main.py
a,b
c,d

Upvotes: 0

jwodder
jwodder

Reputation: 57470

Within main.py, the path to main.py itself is available as the __file__ variable. You can use this to construct paths to other files that you know the location of relative to main.py. In your case, the path to file_to_read.csv can be calculated as:

os.path.join(os.path.dirname(__file__), 'data', 'file_to_read.csv')

Upvotes: 1

Related Questions