需求:
用python插入txt两列数据到excel中,第一列“章节数”,第二列“章节内容”
以下为执行代码:
```python
import pandas as pd
# 读取文本文件
with open('D:\example\chapters.txt', 'r') as file:
lines https://img-mid.csdnimg.cn/release/static/image/mid/ask/6c254291cc654e9d98de69837fb28b76.png "#left")
= file.readlines()
# 去除每行的换行符
chapters = [line.strip() for line in lines]
# 创建 DataFrame
# df = pd.DataFrame({'Chapter': chapters}) # 单一列执行方式:
df = pd.DataFrame({
'章节数': [int(chapter.split(' ')[0]) for chapter in chapters],
'章节名称': [chapter.split(' ')[1] for chapter in chapters]
})
# 保存为 Excel 文件
df.to_excel('D:\example\chapters.xlsx', index=False)
报错提示:
lines = file.readlines()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence