Python甚至在分离函数和下载新的输入文件之后也会损坏文件

2024-04-25 00:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

Mac 10.13.6和Python 3.7.3

我有一个脚本,它运行两个函数,两个函数都读取同一个xlsx文件,然后在进行一些计算之后创建两个新文件。从第一个函数创建的xlsx文件将打开,但当我尝试打开第二个文件时,会弹出一个窗口,要求授予访问权限,然后出现一个错误,说明文件无效/已损坏。一些google让我意识到我不应该在同一个文件上读写两次,但是我想看看我是否可以快速地分别运行这些函数来让它工作

我尝试在一个新的.py文件中单独运行第二个函数,但结果xlsx文件仍然损坏。我甚至尝试下载新的输入文件来单独运行该功能,但现在这些文件也被破坏了。只要我将一个全新的文件粘贴到输入文件夹中供脚本使用,在脚本运行之前,输入文件就会损坏。我到底做了什么

这是我的代码示例function2()function1()完全相同,只是我省略了不同的计算

def function1():
    df = pd.read_excel(file)
    df['filename'] = os.path.basename(file)
    newfile = '/Users/bgoldberg/PythonScripts/HigherEd/Other_Rankings_2020/final_ranked_cc/{}.xlsx'.format(df.filename[0].replace('_', '|').replace('.xlsx', '').replace('BC 2020', 'CC 2020'))
    df2 = pd.read_excel('/Users/bgoldberg/PythonScripts/HigherEd/BC_Rankings_2020/2020 data pull.xlsx', usecols='A, P:DA')
    df = pd.merge(df, df2, on='UnitID', how='left')
    df3 = pd.read_excel('/Users/bgoldberg/PythonScripts/HigherEd/BC_Rankings_2020/program_counts.xlsx', usecols='A, C:Z')
    df = pd.merge(df, df3, on='UnitID', how='left')

    # Some calculations go here that I omitted

    df1 = df1.sort_values(by=['FinalRank'])
    df2 = pd.read_excel(file)
    df2 = pd.merge(df2, df1[['UnitID', 'FinalRank']], on='UnitID', how='left')
    df2['list_name'] = os.path.basename(file).replace('_', '|').replace('.xlsx', '').replace('BC 2020', 'CC 2020')
    cols = df2.columns.tolist()
    cols = cols[-1:] + cols[:-1]
    df2 = df2[cols]
    df2 = df2.sort_values(by=['FinalRank'])
    with pd.ExcelWriter(newfile) as writer:
        df2.to_excel(writer, sheet_name='Final Ranked List', index=False)
        df1.to_excel(writer, sheet_name='Calc Results', index=False)

def function2():
    # essentially same as function1()

globbed_files = glob.glob('/Users/bgoldberg/PythonScripts/HigherEd/Other_Rankings_2020/to_be_ranked_cc/*.xlsx') 
for file in globbed_files:
    function1()
    function2()


Tags: 文件函数dfreadxlsxexcelusersreplace