解决Python Pandas ExcelWriter 中的 'AttributeError: can't set attribute 'book'' 错误
The error "AttributeError: can't set attribute 'book'" is occurring because you are trying to set the 'book' attribute of the writer object using the same object itself, which is not allowed.\n\nTo fix this error, you need to remove the assignment statement "writer.book = writer.book" and directly use the 'book' attribute of the writer object.\n\nHere is the updated code:\n\npython\nimport pandas as pd\nimport os\nimport re\n\nfrom openpyxl import Workbook\n\n# 读取指定路径下的CSV文件\nfolder_path = './自动验单数据/自动验单发生率/四月'\nfile_format = r'\自动验单发生率统计详情\d{8}\.csv'\noutput_folder = 'F:/自动验单数据/4.5-5.5验本数据/'\noutput_file = None\n\nfor filename in os.listdir(folder_path):\n if re.match(file_format, filename):\n date_str = filename[11:19]\n file_path = os.path.join(folder_path, filename)\n yb_data = pd.read_csv(file_path, dtype=object, usecols=[\n '发验机构', '验达机构', '验单上一环节地市', '验单上一环节机构类型', '上下行', '发验时间', '邮件条码'])\n data = yb_data[((yb_data['发验机构'] == '苏州') & (yb_data['发验机构'] == yb_data['验达机构']) & (\n yb_data['验单上一环节机构类型'] == '揽投部') & (yb_data['验单上一环节地市'] == '苏州市') & (yb_data['上下行'] == '上行'))]\n file_name = '4.5-5.5验本数据.xlsx'\n if output_file is None:\n output_file = os.path.join(output_folder, file_name)\n data.to_excel(output_file, index=False)\n else:\n with pd.ExcelWriter(output_file, mode='a', engine='openpyxl') as writer:\n writer.sheets = {ws.title: ws for ws in writer.book.worksheets}\n data.to_excel(writer, index=False, header=False,\n startrow=writer.sheets["Sheet1"].max_row)\n writer.save()\n print(date_str + '匹配完成!')\n# data.to_excel('F:/自动验单数据/验本数据/'+ file_name, index=False)\n else:\n print('全部匹配完成!')\n\n\nThis should resolve the error and allow the code to run without any issues.
原文地址: https://www.cveoy.top/t/topic/pZMt 著作权归作者所有。请勿转载和采集!