Python新手编写批量TSV转CSV脚本报UTF-8解码错误求助
TSV批量转CSV脚本
UnicodeDecodeError修复指南 报错根因
脚本硬编码使用utf-8编码读取TSV文件,而你处理的TSV文件起始位置的字节为0xff,属于带BOM头的UTF-16 LE编码文本(这类编码是Windows版Excel导出TSV时的默认格式,文件起始两个字节固定为0xFF 0xFE),编码不匹配就会直接触发解码异常。
核心修复调整项
- 不再硬编码
utf-8作为唯一读取编码,增加多编码自动适配逻辑,优先识别带0xff开头的UTF-16 LE格式TSV - 移除脚本中未实际使用的
shutil、argparse导入语句,减少冗余依赖 - 输出CSV时改用
utf-8-sig编码,避免Windows系统下Excel打开生成的CSV文件时出现中文乱码
代码修改对照
原问题读取代码
df = pd.read_csv(file, header=0, sep='\t', encoding='utf-8', quoting=3)
替换为自动兼容编码的读取逻辑
# 优先适配UTF-16 LE编码的TSV文件,解决0xff开头的解码错误 try: df = pd.read_csv(file, header=0, sep='\t', encoding='utf-16-le', quoting=3) except UnicodeDecodeError: df = pd.read_csv(file, header=0, sep='\t', encoding='utf-8', quoting=3)
原问题输出代码
df.to_csv(new_filename, encoding='utf-8', index=False)
替换为适配Excel的输出逻辑
df.to_csv(new_filename, encoding='utf-8-sig', index=False)
修复后完整可运行脚本
import os import sys import pandas as pd def main(): if len(sys.argv) == 1: # 过滤隐藏的临时文件,避免误扫无效TSV files = [x for x in os.listdir('.') if x.endswith('.tsv') and not x.startswith('.')] else: files = [sys.argv[1]] for file in files: # 自动适配常见TSV编码 try: df = pd.read_csv(file, header=0, sep='\t', encoding='utf-16-le', quoting=3) except UnicodeDecodeError: df = pd.read_csv(file, header=0, sep='\t', encoding='utf-8', quoting=3) new_filename = f'{file.replace(".tsv", "")}.csv' df.to_csv(new_filename, encoding='utf-8-sig', index=False) print(f'Converted file: {new_filename}') print('Done!') if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者crossrider201
相关产品推荐
相关产品推荐

