无法使用 pandas 保存 excel sheet

can't save excel sheet using pandas

我在做一个大学项目,由于一些限制,我正在使用 python 2.7,因为 pandas 对 python 2 的支持已经结束 我安装了最新发布的版本python 2 即 pandas 0.24.2.

当我尝试执行以下代码时:

    f = "./attendance_report" + "/" + current_course +"("+time.strftime("%d.%m.%Y_%H.%M")+")"+ "_" + "attendance.xlsx"
    writer = pd.ExcelWriter(f, engine='xlsxwriter')
    sheet_name = 'sheet1'
    
    index = [i+1 for i in range(len(checked_names))]
    indexx = [i+1 for i in range(len(registered_names_current_course))]
    
    df = pd.DataFrame(list(zip(index, checked_names, checked_ID)), columns=['Index','Student Name','Student ID'])
    df2 = pd.DataFrame(list(zip(indexx, registered_names_current_course, registered_ID_current_course)), columns=['index','Student_Name','Student_ID'])
    df.to_excel(writer, sheet_name=sheet_name, startrow = 6, index = False)
    df2.to_excel(writer, sheet_name=sheet_name,startrow = len(df)+10, index = False)
    
    for column in df:
        column_width = max(df[column].astype(str).map(len).max(), len(column))
        col_idx = df.columns.get_loc(column)
        writer.sheets[sheet_name].set_column(col_idx, col_idx, column_width)

    for column in df2:
        column_width = max(df2[column].astype(str).map(len).max(), len(column))
        col_idx = df2.columns.get_loc(column)
        writer.sheets[sheet_name].set_column(col_idx, col_idx, column_width)
        
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]
    worksheet.write(0, 0, 'Attendance report of '+current_course+' class', workbook.add_format({'bold': True, 'color': '#E26B0A', 'size': 14, 'align': 'left'}))
    worksheet.write(2, 0, 'Date: '+time.strftime("%d/%m/%Y"),workbook.add_format({'bold': True}))
    worksheet.write(2, 2, 'Time: '+time.strftime("%r"),workbook.add_format({'bold': True}))
    worksheet.write(4, 1, 'Students present',workbook.add_format({'bold': True}))
    worksheet.write(len(df)+8, 1, 'Student absent',workbook.add_format({'bold': True}))
    
    writer.save()

此代码将创建一个 excel 带有某种格式的垃圾。

但是当我尝试执行以下代码时,我收到此错误消息:

File "main.py", line 312, in <module>
    writer.save()
  File "/home/pi/.local/lib/python2.7/site-packages/pandas/io/excel.py", line 1952, in save
    return self.book.close()
  File "/home/pi/.local/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 325, in close
    raise FileCreateError(e)
xlsxwriter.exceptions.FileCreateError: [Errno 2] No such file or directory: './attendance_report/os(08.05.2022_13.37)_attendance.xlsx'

我查看了 pandas 0.24.2 的文档,但在那里找不到任何解决方案。我是 pandas 的新手,这是我第一次使用它。

有人对此有任何想法吗?提前致谢。

你最好检查一下目录是否已经创建。

import os
os.path.exists("attendance_report")