Python: Import excel file using relative path

懵懂的女人 提交于 2020-01-06 06:10:15

问题


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?


回答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'))



回答2:


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.



来源:https://stackoverflow.com/questions/50119792/python-import-excel-file-using-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!