Home > Mobile >  Correct way to refer to a file in a directory treee
Correct way to refer to a file in a directory treee

Time:02-14

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

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

What's the best way to do this?

CodePudding user response:

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')
  • Related