Python:使用相对路径导入Excel文件
问题描述:
我试图导入一个Excel文件,该文件与脚本不在同一文件夹中.我需要在上面找到一个文件夹,然后再放入另一个文件夹(B_folder),然后有文件2_file.xlsx
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
我尝试过:
df = pd.read_excel(r'..\B_folder\2_file.xlsx')
并得到:
FileNotFoundError: [Errno 2] No such file or directory: '..\\B_folder\\2_file.xlsx'
也尝试过:
-
以斜杠代替反斜杠
foreslash instead of backslash
在路径前没有'r'
但是我总是收到上面或这个错误消息:
but I always get the error message above or this one:
OSError: [Errno 22] Invalid argument: '..\\B_folder\2_file.xlsx'
怎么了?
答
感谢您的建议.他们都没有工作,但我找到了解决方案.
Thanks for your suggestions. None of them did work but I found a solution.
df = pd.read_excel(r'./../B_folder/2_file.xlsx')
这对我来说很好用.
因此,如果有人遇到相同的问题,希望对您有所帮助.
So if anybody faces the same problem, I hope this helps.