I have this directory tree:
main_dir
data_folder
file.csv
script_folder
script.py
Inside script.py
I 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')