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) + " ")
修改说明:
- 移除读取时的
errors="ignore",确保完整读取所有UTF-8字符(包括表情) - 写入TXT时明确指定
encoding="utf-8",保证表情符号正确写入 - 用解构和列表拼接简化多层嵌套的if判断,同时补空处理防止索引越界
- 用f-string让字符串拼接更直观易读
内容的提问来源于stack exchange,提问作者林育正
相关产品推荐
相关产品推荐

