简体   繁体   中英

Read Excel file that is located outside the folder containing the module into Pandas DataFrame

I want to read an excel file into pandas DataFrame. The module from which I want to read the file is inputs.py and the excel file (schoolsData.xlsx) that I want to read is outside the folder containing the module. I'm doing it like this in my code

def read_data_excel(path):
    df_file = pd.read_excel(path)
    return df_file
    
school_data = read_data_excel('../schoolsData.xlsx')

Error: No such file or directory: '../schoolsData.xlsx'

The strange thing is that it works fine when I run the function containing this code locally but I get an error when I run the function after installing my published package from PyPi.

What is the right way to do it? Also would is it possible to read the file normally from the installed distributable that is a compressed folder?

在此处输入图像描述

The error could be arised because of the current working directory is different when you execute in local than when you execute after installing. Take a look to this to generalize the path without hardcoding it.

Your code should work. Try this to check the folder you are at:

import os 
os.path.dirname(os.path.realpath(__file__))

You can always do

df_file = pd.read_excel("../schoolsData.xlsx")

".." will go back outside the current folder and this will be a relative reference.

You can always define an absolute path to that folder as well (that starts from C://whatever).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM