【问题标题】:how to extract a specific lines and columns from a file and save it in another file如何从文件中提取特定的行和列并将其保存在另一个文件中
【发布时间】:2019-09-20 13:33:27
【问题描述】:

我有一个巨大的文件,我需要提取特定的行和列,然后将它们保存在输出文件中。我有大约 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"))

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

【问题讨论】:

  • 4900这个数量有什么意义?为什么您希望提取最后一列?您的 find 调用,即使它在有效条目上运行,也只会将索引值返回到文本行中。因此,您只想获取单行的最后一列值,还是要处理所有行并生成仅包含第一列和最后一列的另一个表?

标签: python file line extract


【解决方案1】:

如果你想读取你显示的数据,只提取数据行,解析它们以提取第一列和最后一列,然后只将第一列和最后一列写入文件,你可以这样做:

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

这应该能够处理非常大的文件,因为我不会将整个文件读入内存,而是逐行读取和写入。

【讨论】:

  • 谢谢,我尝试使用你的模块,它的工作,但输出不仅是我需要的部分,它从文件的开头写入每个列 [0] 和列 [7] '不知道为什么模块不符合条件 (if len(columns) == 8 and columns[0] != 'nuclide' and columns[0][0] != '-':)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-21
  • 2021-02-13
  • 2020-01-03
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多