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

Python读取CSV打印列表出现特殊字符,指定列取最大值问题排查

你遇到的异常字符是UTF-8 BOM(字节顺序标记),是Windows平台下Excel等软件导出UTF-8编码CSV时默认在文件头部添加的特殊标识,Python默认读取UTF-8文件时不会自动过滤这个标识,就会把它解析成拼在第一行第一个列名前。

解决方法非常简单:只需要在打开CSV文件时指定编码为utf-8-sig,这个编码会自动跳过开头的BOM标记,同时你开头冗余的未关闭文件打开操作可以直接删除,修正后的代码如下:

#!/usr/bin/env python3
import csv

MaxValue = 0
LettLocation = 0

print('Enter column letter:')
FindChar = input()

with open("Book1.csv", newline='', encoding='utf-8-sig') as f:
  Reader = csv.reader(f)
  FirstRow = next(Reader)
  print(FirstRow)
  for Incre in range(len(FirstRow)):
    if FirstRow[Incre] == FindChar:
        LettLocation = Incre
        break
    
  for row in Reader:
    FirstValue = int(row[LettLocation])
    if MaxValue < FirstValue:
        MaxValue = FirstValue

print("At column", FindChar, "The highest value is:", MaxValue)

修改后再运行就能得到正常的首行列名列表,列匹配逻辑也能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 23:39:04