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

如何用Python去除ANSI编码CSV文件中的LF换行符?

解决CSV文件LF换行符去除问题

你的问题核心在于:

  • strip()仅去除字符串首尾的换行符,无法处理文件中间的LF
  • pandas的skip_blank_lines=True是跳过空行,而非移除单元格内的换行符

以下是几种可行方案:

方案1:全局替换所有LF换行符

如果需要移除文件中所有LF(无论位置),直接用字符串替换即可:

with open(csvTable, 'r', encoding='ANSI') as f:
    raw_csv = f.read()
    # 将所有LF换行符替换为空,可根据需求改为其他字符(如空格)
    clean_csv = raw_csv.replace('\n', '')

with open(csvTable2, 'w', encoding='ANSI') as f:
    f.write(clean_csv)

方案2:精准处理单元格内的换行符(保留正常行分隔)

如果LF是单元格内的非法换行,需要保留CSV的正常行结构,用csv模块更安全:

import csv

with open(csvTable, 'r', encoding='ANSI', newline='') as infile:
    reader = csv.reader(infile)
    with open(csvTable2, 'w', encoding='ANSI', newline='') as outfile:
        writer = csv.writer(outfile)
        for row in reader:
            # 遍历每个单元格,移除其中的LF换行符
            cleaned_row = [cell.replace('\n', '') for cell in row]
            writer.writerow(cleaned_row)

方案3:用pandas处理单元格内换行符

如果习惯用pandas,需遍历单元格替换换行符:

import pandas as pd

data_set = pd.read_csv(data_file, encoding='ANSI')
# 仅对字符串类型的单元格替换LF换行符
data_set = data_set.applymap(lambda x: x.replace('\n', '') if isinstance(x, str) else x)
data_set.to_csv(target_file, index=False, encoding='ANSI')

注意:如果你的CSV行分隔符就是LF,不要用方案1,否则会把所有行合并成一行,此时方案2或3更合适。

内容的提问来源于stack exchange,提问作者J. Skinner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:40:29