python - 批量 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()
解决方案
当 CSV 被读入 Pandas 时,它使用utf-8
编码,但是,文件上可能使用了其他编码格式
在这行代码中:
df = pd.read_csv(file, header=0, sep='\t', encoding='utf-8', quoting=3)
尝试设置encoding
为不同的格式。
您可以尝试许多不同的格式,这里是完整列表。我建议使用记事本或其他文本编辑器打开文件,然后使用 utf-8 编码另存为 CSV。
推荐阅读
- amazon-web-services - 无法使用 terraform 使用最少的 IAM 策略创建带有实例标记的 ec2 实例
- python - 如何循环消息
- python - Django ModelAdmin get_urls 未正确注册
- dc.js - dc.js 中的相关矩阵
- flutter - 颤抖,飞镖。如何向地图添加键和值
- reactjs - 在 reactjs 中使用 Sass 和 antdesign
- node.js - Discord JS V13 无法向公会所有者发送消息
- java - Spring SQS @SqsListener 与 BeanPostProcessor
- birt - 如何读取组内的所有详细行并进行一些计算
- html - 如何在 CSS 中制作具有完美圆角边缘的半圆线?