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

如何解决Python合并CSV文件时出现的UnicodeDecodeError编码报错

问题根源

报错是编码不匹配导致:错误信息中提到的0xb0是温度单位符号°在Latin-1(ISO-8859-1)编码下的字节值,你的正式数据CSV文件不是Python默认的UTF-8编码,所以读取失败。


修复方案

1. 核心修改逻辑

所有打开文件的位置(open、pd.read_csv)统一指定正确的编码,优先测试latin1,如果不匹配可替换为cp1252、gbk这类常见编码。

2. 优化冗余逻辑

原代码对每个文件重复打开3次,可合并逻辑减少IO操作,同时补充边界判断避免触发其他异常。


修正后的完整代码

import numpy as np
import os
import pandas as pd
import csv

path = '/Users/laurendonati/Desktop/AssateagueIsland_Data/CTD Pond Drivers /17B/17B_CSV'
df_list = []
# 可根据实际编码替换该参数,可选值:latin1/cp1252/gb18030
file_encoding = 'latin1'

for each in os.scandir(path):
    # 跳过子文件夹等非文件条目
    if not each.is_file():
        continue
    # 单次读取确认表头起始行
    with open(each.path, 'r', encoding=file_encoding) as f:
        substring = "Date/time"
        st = 0
        for i, row in enumerate(f):
            if substring in row:
                st = i
                break
    # 直接读取有效数据
    df_app = pd.read_csv(each.path, skiprows=st, encoding=file_encoding)
    df_list.append(df_app)

# 合并所有数据表
df = pd.concat(df_list, ignore_index=True)

# 原有计算逻辑保留
temp = df["Temperature[°C]"]
Conductivity = df["2:Spec.cond.[mS/cm]"]
SpecificConductance = Conductivity / (1 + 0.02 * (temp - 25))
df['Specific Conductivity'] = SpecificConductance

# 导出时指定UTF-8编码避免后续乱码
df.to_csv('/Users/laurendonati/Desktop/Tester/Round_T_wo.csv', index=False, encoding='utf-8')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:45:04