Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Import excel file using relative path

Tags:

I tried to import an excel file which is not within the same folder than the script. I need to get one folder above, then into another folder (B_folder) and there is file 2_file.xlsx

I tried:

df = pd.read_excel(r'..\B_folder\2_file.xlsx')

and got:

FileNotFoundError: [Errno 2] No such file or directory: '..\\B_folder\\2_file.xlsx'

also tried:

  • foreslash instead of backslash

  • without the 'r' before path

but I always get the error message above or this one:

OSError: [Errno 22] Invalid argument: '..\\B_folder\2_file.xlsx'

what is wrong?

like image 857
MaMo Avatar asked May 01 '18 16:05

MaMo


People also ask

How do I give a relative a file path in Python?

A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.

How do you convert relative path to absolute path in Python?

path. relpath(path) makes a absolute path to relative path. And if the path provided is itself a relative path then the function returns the same path.


1 Answers

Thanks for your suggestions. None of them did work but I found a solution.

df = pd.read_excel(r'./../B_folder/2_file.xlsx')

This works perfectly fine for me.

So if anybody faces the same problem, I hope this helps.

like image 88
MaMo Avatar answered Oct 11 '22 18:10

MaMo