Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas read CSV from sibling directory

+-- parent_dir
|   +-- dir1
|       +-- script.py 
|   +-- dir2
|       +-- mycsv.csv

How can we read mycsv.csv from within the script.py script. We've tried pd.read_csv("../dir2/mycsv.csv") and received the error FileNotFoundError: [Errno 2] No such file or directory:.

like image 709
Canovice Avatar asked May 12 '26 13:05

Canovice


2 Answers

presumably you are not actually running it from inside dir1 (even though you think you are)

however you can do

 file_dir = os.path.dirname(__file__)
 csv_path = os.path.join(file_dir,"..","dir2","mycsv.csv")

and then it should work no matter where you run it from

as an aside you can try

print(os.getcwd())

to see where you are actually executing it from

like image 98
Joran Beasley Avatar answered May 15 '26 03:05

Joran Beasley


This depends more on the place you're trying to run script.py from.

For example, if you are in parent_dir and you do python dir1/script.py, then you would refer mycsv.csv as dir2/mycsv.csv.

So, you would either need to specify the full path e.g. /home/user/parent_dir/dir2/mycsv.csv.

If the location is always relative to script.py as you mentioned; you would do as indicated in the answer above.

like image 45
saedx1 Avatar answered May 15 '26 04:05

saedx1