Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct way to refer to a file in a directory treee

I have this directory tree:

 main_dir
     data_folder
       file.csv
     script_folder
           script.py

Inside script.pyI have:

df=pd.read_csv('file.csv')

What is the correct way to refers to the file.csv in the pandas read_csv

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t want to use the full path "home/user/main_folder/data/file.csv"

What’s the best way to do this?

>Solution :

It depends on where your script is executed (current working directory). To use relative path from your script, use __file__ variable:

import pandas as pd
import pathlib

data_dir = pathlib.Path(__file__).parent.parent / 'data_dir'

df = pd.read_csv(data_dir / 'file.csv')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading