使用熊猫在python中处理大文本文件的问题

时间:2018-11-03 13:50:48

标签: python

我有一个文本文件,如下例所示:

small example

0,1,2,3,4,5,6
chr1,144566,144597,30,chr1,120000,210000
chr1,154214,154245,34,chr1,120000,210000
chr1,228904,228935,11,chr1,210000,240000
chr1,233265,233297,13,chr1,210000,240000
chr1,233266,233297,58,chr1,210000,240000
chr1,235438,235469,36,chr1,210000,240000
chr1,262362,262393,16,chr1,240000,610000
chr1,347253,347284,12,chr1,240000,610000
chr1,387022,387053,38,chr1,240000,610000

我要删除第一行,而不是comma separated,而是制作一个tab separated文件。像预期的输出一样:

expected output

chr1    144566  144597  30  chr1    120000  210000
chr1    154214  154245  34  chr1    120000  210000
chr1    228904  228935  11  chr1    210000  240000
chr1    233265  233297  13  chr1    210000  240000
chr1    233266  233297  58  chr1    210000  240000
chr1    235438  235469  36  chr1    210000  240000
chr1    262362  262393  16  chr1    240000  610000
chr1    347253  347284  12  chr1    240000  610000
chr1    387022  387053  38  chr1    240000  610000

我正在尝试使用pythonpandas中进行此操作。我写了这段代码,但没有返回我想要的。你如何解决?

import pandas
file = open('myfile.txt', 'rb')
new =[]
for line in file:
    new.append(line.split(','))
    df = pd.DataFrame(new)
    df.to_csv('outfile.txt', index=False)

2 个答案:

答案 0 :(得分:3)

import pandas as pd    
df = pd.read_csv('myfile.txt', header=0)
df.to_csv('outfile.txt', sep='\t', index=None, header=False)

答案 1 :(得分:1)

根据文件的大小,避免使用Pandas并使用基本的Python I / O可能是一个更有效的方法。这样,您不必将整个文件读入内存,而是逐行读取并转储到带有制表符分隔的新文件中:

with open("myfile.txt", "r") as r:
    with open("myfile2.txt", "w") as w:
        for line in r:
            w.write("\t".join(line.split(',')))

myfile2.txt现在是myfile.txt的制表符分隔版本。