Python大型.tsv文件到.csv fi

2024-09-27 04:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

实际上,下面的代码可以成功地将.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()

我知道通过阅读一个大文件,我可以使用以下代码:

^{pr2}$

但我不知道如何将这两个代码合并为一个,并正确地将一个大的.tsv文件转换为.csv文件


Tags: 文件csv函数代码fromimportreconvert
2条回答

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

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)

对于大文件,使用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')

相关问题 更多 >

    热门问题