我想通过列将文本文件拆分为多个文件

时间:2017-01-24 23:54:47

标签: python python-2.7

我有一个文件,其中第一列重复模式如下,

1999.2222 50 100
1999.2222 42 15 
1999.2222 24 35
1999.2644 10 25
1999.2644 10 26
1999.3564 65 98
1999.3564 45 685
1999.3564 54 78
1999.3564 78 98

我想把这个文件分成三个文件

文件1:

1999.2222 50 100
1999.2222 42 15 
1999.2222 24 35

file2的:

1999.2644 10 25
1999.2644 10 26

file3的:

1999.3564 65 98
1999.3564 45 685
1999.3564 54 78
1999.3564 78 98

我怎么能像这样分开?感谢:)

1 个答案:

答案 0 :(得分:1)

itertools.groupby 可能是您追求的最佳选择。

import itertools

with open('file.txt', 'r') as fin:
    # group each line in input file by first part of split
    for i, (k, g) in enumerate(itertools.groupby(fin, lambda l: l.split()[0]), 1):
        # create file to write to suffixed with group number - start = 1
        with open('file{0}.txt'.format(i), 'w') as fout:
            # for each line in group write it to file
            for line in g:
                fout.write(line.strip() + '\n')