Python: Import excel file using relative path [duplicate]
Asked Answered
P

2

7

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?

Proceeds answered 1/5, 2018 at 16:2 Comment(7)
Windows or Mac?Thermotaxis
working with WindowsProceeds
Try specifying the full path...Thermotaxis
this works but I need the relative one cause I have to hand it inProceeds
Your file path must be wrong then.Thermotaxis
Remember that the relative path is calculated with respect to the folder where your script runs.Redmond
checked that. the structure looks like this: one folder contains two folders, one with scripts and one with excel files (B_folder). So starting with the script location I go one folder up and then into B_folder. Is the coding I posted korrekt to do that?Proceeds
P
8

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.

Proceeds answered 9/5, 2018 at 11:8 Comment(0)
H
1

You can calculate the absolute path first:

import os.path
fullpath = os.path.abspath('..\B_folder\2_file.xlsx')

And use it to open the Excel file.

If the \ do not work, you can use this syntax:

fullpath = os.path.abspath(os.path.join('..', 'B_folder', '2_file.xlsx'))
Hyperplasia answered 1/5, 2018 at 16:17 Comment(1)
tried that. fullpath looks like this: 'C:\\Users\\B_folder\x02_file.xlsx' but df = pd.read_excel(fullpath) still does not work. even removed the number in front of the filename but it seems like this is not the problemProceeds

© 2022 - 2024 — McMap. All rights reserved.