读取文件时,如何仅拾取以整数开头的行?

2024-09-27 22:22:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个长文本文件,几行以整数值开始,例如2019等,还有几行以非整数值开始,例如KP、AB、XY。我想选取第一个整数行,将其与非整数行合并,并将其保存在文本文件中。然后,获取第二个整数行和concat以及后面的非整数行,并保存在同一个文本文件中,依此类推。 示例数据文件如下所示

'''

2019    15  3   13  57  22.3    34  73.71   0   2.2
AT  EP  357 36.36                       
ST  ES  358 17.22                       
ATT T   357 53.26                       
UO  ES  358 19.3                        
2019    11  4   7   18  58  33.17   70  1.1 2.3
PDA EP  743 8.6                     
TTY ES  743 23.73                       
NIL EP  743 12.75                       
2019    10  4   11  19  4.6 33.16   73.71   0   2.5
CET IP  1119    59.6                        
CET EP  1119    37.12                       
TU  ES  1119    59.36                       
THW EP  1119    37                      
2019    10  6   5   25  57.2    33.14   73.65   3.1 3.1
CET ES  526 50.28                       
CET EP  526 28

这里我们需要对第一组整数行和非整数行进行合并,即

    2019    15  3   13  57  22.3    34  73.71   0   2.2
    AT  EP  357 36.36                       
    ST  ES  358 17.22                       
    ATT T   357 53.26                       
    UO  ES  358 19.3

在第二种情况下,我们对集合子集进行concat,因此是一个

2019    11  4   7   18  58  33.17   70  1.1 2.3
PDA EP  743 8.6                     
TTY ES  743 23.73                       
NIL EP  743 12.75

Tags: abes整数attatepstnil
3条回答
f = open("data.txt")

for line in f:
    try:
        x = int(line.split(" ")[0])  # can determine integer otherwise in except block
        print(x)
    except:
        continue;

这样做:

import re
for line in f.readlines():
    if re.match("^2019", line): print("Yeah!")

i是给你数字0, 1, 2, ...,即行号减去1。除非您有超过2019行,否则if将不会计算为True

相反,您可以查看line变量中的行。每个回合都是一个字符串,因此您可以查看它的第一个字符并查看if it is a digit

for line in f:
    if line[0].isdigit():
        print(line)

要将整数起始行和其他行写入2个单独的文件,请打开2个这样的文件,然后根据if使用print进行写入:

integers_file = open("integers.txt", "w")
others_file = open("others.txt", "w")

for line in f:
    if line[0].isdigit():
        print(line, file=integers_file, end="")
    else:
        print(line, file=others_file, end="")

integers_file.close()
others_file.close()

我们将end=""传递给print以避免额外的新行,因为一个新行来自读取文件的行

相关问题 更多 >

    热门问题