【问题标题】:Pandas Excel import only works for a single function call - error on second function callPandas Excel 导入仅适用于单个函数调用 - 第二个函数调用出错
【发布时间】:2017-12-01 17:36:31
【问题描述】:

在第一次函数调用后,我无法在 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

我很困惑,为什么这有效一次而不是两次?

谢谢

【问题讨论】:

  • 您传递给第二个函数的文件已损坏或无效文件。尝试将相同的文件传递给您要传递给 fiist 函数的第二个文件并检查它是否有效
  • 不,它是同一个文件。没有任何改变。

标签: django excel pandas


【解决方案1】:

您可以使用read_excel 同时加载两张纸。结果将是一个包含两个数据框的字典。

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'])

【讨论】:

  • 这是确保安全的最佳方法。谢谢。
  • 没问题。随意将其标记为正确答案;)
【解决方案2】:

从这个答案: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) 来重置指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2018-01-17
    • 2022-01-07
    相关资源
    最近更新 更多