Python pandas read CSV from sibling directory

Viewed 180
+-- 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:.

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

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.

Related