从一个文件读取数据并写入多个文件

时间:2014-09-30 17:31:56

标签: python bash

我有一个包含大量数据的文件,如下所示:

inputfile中:

     MOLECULE=AMMONIA
     N                0.0000000000   0.0000000000  10.0000000000
     H                0.5883730000   0.5883730000  10.5883730000
     H               -0.5883730000  -0.5883730000  10.5883730000
     MOLECULE=AMMONIA
     N               -0.3476074320  -0.2347533040   9.3713354700
     H                0.2407655680   0.3536196960   9.9597084700
     H               -0.9359804320  -0.8231263040   9.9597084700
     MOLECULE=AMMONIA
     N               -1.2368117200  -0.5350340580   8.7012089080
     H               -0.6484387200   0.0533389420   9.2895819080
     H               -1.8251847200  -1.1234070580   9.2895819080

我需要一个bash脚本来读取此文件中的所有行,并将其写入多个输出文件,如下所示:

outputfile1:

     MOLECULE=AMMONIA
     N                0.0000000000   0.0000000000  10.0000000000
     H                0.5883730000   0.5883730000  10.5883730000
     H               -0.5883730000  -0.5883730000  10.5883730000

outputfile2:

     MOLECULE=AMMONIA
     N               -0.3476074320  -0.2347533040   9.3713354700
     H                0.2407655680   0.3536196960   9.9597084700
     H               -0.9359804320  -0.8231263040   9.9597084700

outputfile3:

     MOLECULE=AMMONIA
     N               -1.2368117200  -0.5350340580   8.7012089080
     H               -0.6484387200   0.0533389420   9.2895819080
     H               -1.8251847200  -1.1234070580   9.2895819080

我尝试了readarray,但它将所有内容存储在一维阵列中,并带有换行符。你能用单行或小脚本帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

with open('path/to/input') as infile:
    i = 0
    f = open('outfile%d'%i, 'w')
    for line in infile:
        if line.lstrip().startswith("MOLECULE"):
            f.close()
            i += 1
            f = open('outfile%d'%i, 'w')
        f.write(line)