将Python处理大型.tsv文件转换为.csv文件

3

实际上,下面的代码可以成功将 .tsv 文件转换为 .csv 文件,但是当文件很大(例如超过 1GB)时,在 read 函数中会出现 MemoryError

import re
tsv = open('tsv.tsv', 'r')
fileContent =  tsv.read()
fileContent = re.sub("\t", ",", fileContent) # convert from tab to comma
csv_file = open("csv.csv", "w")
csv_file.write(fileContent)
csv_file.close()

我知道读取大文件可以使用以下代码:

with open("data.txt") as myfile:
    for line in myfile:

但我不知道如何将这两个代码组合成一个,并使其正常工作,将大尺寸的 .tsv 文件转换为 .csv 文件。

2个回答

4

只要直接把你的两个片段粘贴在一起:

with open("data.txt", 'r') as myfile:
  with open("csv.csv", 'w') as csv_file:
    for line in myfile:
      fileContent = re.sub("\t", ",", line)
      csv_file.write(fileContent)

我添加了一行代码,因为我的输出CSV文件中有逗号导致格式出现问题:for line in myfile: line = line.replace(",", '.') fileContent = re.sub("\t", ",", line) - Worm

2
对于大文件,请使用pandas而不是纯Python:
import pandas as pd
dfs = pd.read_csv('file.tsv', sep='\t', chunksize=50)
for df in dfs:
    df.to_csv('file.csv', sep=',', mode='a')

@androidnewbie 我已经编辑了我的答案,还请阅读pandas文档 http://pandas.pydata.org/pandas-docs/version/0.20.2/generated/pandas.DataFrame.to_csv.html - Dmitrii K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接