Python大型.tsv文件到.csv文件
事实上,下面的代码可以成功地将Python大型.tsv文件到.csv文件,python,csv,Python,Csv,事实上,下面的代码可以成功地将.tsv文件转换为.csv文件,但是,当文件较大(如超过1GB)时,它在读取功能中有一个内存错误 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(fil
.tsv
文件转换为.csv
文件,但是,当文件较大(如超过1GB)时,它在读取
功能中有一个内存错误
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文件对于大文件,请使用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')
只需将两个片段直接粘贴在一起:
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)
@androidnewbie我已经编辑了我的答案,也请阅读熊猫文档,我添加了一行,因为我的文件中有逗号打断了我的输出CSV:
行:line=line.replace(“,”,“.”)fileContent=re.sub(“\t”,”,“,”,line)