在第一次函数调用后,我无法在Pandas中打开第二个excel工作表。
此处import_info
有效,但import_data
在尝试以完全相同的方式打开相同的Excel文件时出错。
文件路径仍在,但我收到了expected str, bytes or os.PathLike object, not NoneType
:
# get the account info
a = import_info ( file )
# get the data
cf = import_data ( file )
第一个功能正常工作:
def import_info ( file ):
xl = pd.ExcelFile ( file )
df = xl.parse ( "info", index = False )
data = df [ ... ]
return data
获取路径错误的第二个函数:
def import_data ( file ):
xl = pd.ExcelFile ( file )
df = xl.parse ( "data", index = False )
data = df [ ... ]
return data
我很困惑,为什么这个工作一次但不是两次?
谢谢
答案 0 :(得分:0)
从这个回答:Python pandas - Does read_csv keep file open?,似乎pandas会在第一次通话时保持文件打开,这就解释了为什么在第二次通话时无法访问它。
如果file
参数是文件的路径,我建议您首先使用with open
python方法处理打开/关闭文件:
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)
来重置指针。
答案 1 :(得分:0)
您可以使用circle-stroke-width
同时加载两张纸。结果将是两个数据帧的dictonary。
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'])