You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python CSV模块问题:列名显示为第一行而非表头(LibreOffice打开)

解决CSV表头被识别为数据行的问题

问题根源

大概率是编码不兼容或者换行符处理异常,导致LibreOffice无法正确区分表头和数据行。Python默认用UTF-8编码写入文件,但Windows环境下的LibreOffice可能默认以GBK等编码读取,或者换行符被自动转换后打乱了CSV的结构。

修复办法

办法1:使用UTF-8带BOM编码写入

用utf-8-sig编码写入,文件开头会添加BOM标记,让LibreOffice能正确识别表头:

import csv

def write_csv():
    with open(f'RTD 1.csv', 'w', encoding='utf-8-sig') as csvfile:
        writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=['one', 'two', 'three'])
        writer.writeheader() 
        writer.writerow({'one': 1, 'two': 2, 'three': 3})

办法2:添加newline=''参数

根据Python官方文档,使用csv模块时建议打开文件指定newline='',避免换行符被自动转换:

import csv

def write_csv():
    with open(f'RTD 1.csv', 'w', newline='', encoding='utf-8-sig') as csvfile:
        writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=['one', 'two', 'three'])
        writer.writeheader() 
        writer.writerow({'one': 1, 'two': 2, 'three': 3})

验证步骤

修改代码后重新生成CSV文件,用LibreOffice打开时,在导入向导中确认编码选择UTF-8、分隔符选择逗号,即可看到表头正常显示。

内容的提问来源于stack exchange,提问作者Mika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:37:27