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

Python中CSV转TXT时如何保留表情符号格式?

CSV转TXT保留表情符号的解决方案

你的代码里导致表情丢失的核心问题有两个:

  • 读取CSV时加了errors="ignore",会直接丢弃无法解码的字符(包括部分特殊表情)
  • 写入TXT文件时没指定编码,系统默认编码(比如Windows下的GBK)无法兼容UTF-8表情,导致乱码或丢失

修改后的代码如下:

import csv

file_name = input("Your file name:")
with open(file_name, newline='', encoding="utf-8") as csvfile:
    rows = list(csv.reader(csvfile))

with open('total.txt', 'w', encoding="utf-8") as output_file:
    for row in rows[1:]:
        # 解构列数据,补空避免索引越界
        _, name, content, _, tag, editor_note = row + [""]*6
        
        line_parts = []
        if tag:
            line_parts.append(f"[{tag}]")
        line_parts.append(f"{name}:{content}")
        if editor_note:
            line_parts.append(f"小編:{editor_note}")
        
        output_file.write(" ".join(line_parts) + "   ")

修改说明:

  1. 移除读取时的errors="ignore",确保完整读取所有UTF-8字符(包括表情)
  2. 写入TXT时明确指定encoding="utf-8",保证表情符号正确写入
  3. 用解构和列表拼接简化多层嵌套的if判断,同时补空处理防止索引越界
  4. 用f-string让字符串拼接更直观易读

内容的提问来源于stack exchange,提问作者林育正

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:42:41