Traceback (most recent call last): File "D:/trade/汇总分析.py", line 128, in <module> for j, row in enumerate(reader): File "C:\Users\LXC\AppData\Local\Programs\Python\Python37\lib\csv.py", line 111, in __next__ self.fieldnames File "C:\Users\LXC\AppData\Local\Programs\Python\Python37\lib\csv.py", line 98, in fieldnames self._fieldnames = next(self.reader) UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 16: illegal multibyte sequence
时间: 2023-07-20 10:38:24 浏览: 141
这个错误是因为在读取csv文件时,编码格式不匹配所致。一般情况下,csv文件的编码格式为UTF-8或者ASCII,但是有些csv文件的编码格式是GBK或者GB2312,所以需要在读取csv文件时指定文件的编码格式。你可以尝试如下代码:
```python
import csv
from docx import Document
from docx.shared import Inches
# 定义要输出的列
fieldnames = ['Name', 'Age']
# 循环处理每个csv文件
for i in range(1, 11):
# 打开csv文件
with open(f'example_{i}.csv', 'r', encoding='gbk') as f:
reader = csv.DictReader(f)
# 获取前5行数据
rows = []
for j, row in enumerate(reader):
if j == 5:
break
rows.append(row)
# 创建输出的doc文件
document = Document()
document.add_heading(f'My CSV Data {i}', 0)
table = document.add_table(rows=1, cols=2)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Age'
for row in rows:
row_cells = table.add_row().cells
row_cells[0].text = row['Name']
row_cells[1].text = row['Age']
document.add_page_break()
document.save(f'output_{i}.docx')
```
在这个示例代码中,我们在打开csv文件时,通过指定encoding参数为'gbk'来指定文件的编码格式。如果你的csv文件编码格式不是gbk,你可以将'gbk'替换为你csv文件的编码格式。
阅读全文