如何从文件中提取特定的行和列并将其保存在另一个文件中

how to extract a specific lines and columns from a file and save it in another file

我有一个大文件,我需要提取特定的行和列,然后将它们保存在输出文件中。我有大约 1000 个文件,所以我想对所有文件执行相同的操作,然后我将有 1000 个包含我想要的数据的新文件。我是 python 的新手,做起来很困难。

我已经尝试读取文件并将所有行保存在列表中,但我不能做更多。

Cycle 3 Down - 20_3.2_10_100_1                                                  
units of measure: atoms / barn-cm                                             
time (years)   

nuclide   1.000E-02 3.000E-02 1.000E-01 3.000E-01 1.000E+00 3.000E+00 1.000E+01

--------  --------- --------- --------- --------- --------- --------- --------- 

 ag109   9.917E-07 9.917E-07 9.917E-07 9.917E-07 9.917E-07 9.917E-07 9.917E-07
 am241   1.301E-07 1.389E-07 1.695E-07 2.565E-07 5.540E-07 1.349E-06 3.577E-06
 am243   8.760E-08 8.760E-08 8.760E-08 8.760E-08 8.759E-08 8.757E-08 8.752E-08
 cs133   2.083E-05 2.101E-05 2.112E-05 2.112E-05 2.112E-05 2.112E-05 2.112E-05
 eu151   4.979E-10 5.579E-10 7.679E-10 1.367E-09 3.458E-09 9.368E-09 2.935E-08
 eu153   1.128E-06 1.132E-06 1.132E-06 1.132E-06 1.132E-06 1.132E-06 1.132E-06
 gd155   4.398E-10 5.831E-10 1.081E-09 2.477E-09 7.048E-09 1.778E-08 3.786E-08
 mo95    1.317E-05 1.351E-05 1.466E-05 1.716E-05 1.960E-05 1.979E-05 1.979E-05
 nd143   1.563E-05 1.587E-05 1.626E-05 1.641E-05 1.641E-05 1.641E-05 1.641E-05
 nd145   1.181E-05 1.181E-05 1.181E-05 1.181E-05 1.181E-05 1.181E-05 1.181E-05
 np237   2.898E-06 2.944E-06 2.982E-06 2.985E-06 2.986E-06 2.989E-06 3.017E-06

这是我要保存的文件部分。我想保存核素名称和最后一列的值。

nuclide=[]
with open ('filename.txt','r') as myfile:
     for line in myfile:
         nuclide.append(line)
     print(nuclide[4900]).find("ag109"))

我应该有一个包含核素符号和最后一列值的列表

如果您想读取显示的数据,只提取数据行,解析它们以提取第一列和最后一列,然后将第一列和最后一列写入文件,方法如下:

import re

with open("/tmp/input.txt") as ifh:
    with open("/tmp/output.txt", "w") as ofh:
        while True:
            line = ifh.readline()
            if not line:
                break
            columns = re.split(r"\s+", line.strip())
            if len(columns) == 8 and  columns[0] != 'nuclide' and columns[0][0] != '-':
                ofh.write("{} {}\n".format(columns[0], columns[7]))

我试图对文件开头的内容超级宽容。这是获取您在问题中提供的数据的输出,将所有内容原封不动地粘贴到文件中,然后 运行 这个程序覆盖它。

/tmp/output.txt:

ag109 9.917E-07
am241 3.577E-06
am243 8.752E-08
cs133 2.112E-05
eu151 2.935E-08
eu153 1.132E-06
gd155 3.786E-08
mo95 1.979E-05
nd143 1.641E-05
nd145 1.181E-05
np237 3.017E-06

这应该能够处理非常大的文件,因为我没有将整个文件读入内存,而是一行一行地读写。