首页 > 解决方案 > 批量 tsv 到 csv 脚本

问题描述

我对 Python 很陌生,我编写了这个脚本,将 tsv 文件批量转换为 csv。我不断收到错误消息并花费数小时试图查看我做错了什么。对此的任何帮助将不胜感激。错误代码是“UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte”

import os
import sys
import shutil
import pandas as pd
import argparse

def main():
    if len(sys.argv) == 1:
        files = [x for x in os.listdir('.') if x.endswith('.tsv')]
    else:
        files = [sys.argv[1]]
    
    for file in files:
        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', index=False)
        print(f'Converted file: {new_filename}')

    print('Done!')

if __name__ == '__main__':
    main()

标签: pythonpython-3.xpandasdataframecsv

解决方案


当 CSV 被读入 Pandas 时,它使用utf-8编码,但是,文件上可能使用了其他编码格式

在这行代码中:

df = pd.read_csv(file, header=0, sep='\t', encoding='utf-8', quoting=3)

尝试设置encoding为不同的格式。

您可以尝试许多不同的格式,这里是完整列表。我建议使用记事本或其他文本编辑器打开文件,然后使用 utf-8 编码另存为 CSV。


推荐阅读