pandasExcel导入仅适用于单个函数调用 – 第二个函数调用时出错

在第一次函数调用之后,我失去了在pandas中打开第二个excel工作表的能力。

这里的import_info工程,但import_data给我一个错误,尝试以完全相同的方式打开同一个Excel文件。

文件path仍然存在,但我得到expected str, bytes or os.PathLike object, not NoneType

 # get the account info a = import_info ( file ) # get the data cf = import_data ( file ) 

第一个function正常工作:

 def import_info ( file ): xl = pd.ExcelFile ( file ) df = xl.parse ( "info", index = False ) data = df [ ... ] return data 

第二个得到path错误的函数:

 def import_data ( file ): xl = pd.ExcelFile ( file ) df = xl.parse ( "data", index = False ) data = df [ ... ] return data 

我很困惑,为什么这个工作一次,但不是两次?

谢谢

您可以使用read_excel同时加载两张表。 结果将是与两个dataframedictonary。

 def get_data(file): return pd.read_excel(file, ['info', 'data']) def prepare_info_df(df): ... return data def prepare_data_df(df): ... return data df_dict = get_data(file) info_df = prepare_info_df(df_dict['info']) data_df = prepare_data_df(df_dict['data']) 

从这个答案: Pythonpandas – read_csv保持文件打开? ,似乎pandas保持从第一个电话打开文件,这将解释为什么你不能访问它在你的第二个电话。

如果file参数是file的path,我build议您首先with open python方法来处理打开/closures文件:

 def import_info(file): with open(file, 'r') as open_file: xl = pd.ExcelFile(open_file) df = xl.parse( "info", index = False ) data = df[...] return data 

如果file参数是类似于对象的文件,则可能需要调用seek(0)来重置指针。