我有一个长文本文件,几行以整数值开始,例如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
这样做:
i
是给你数字0, 1, 2, ...
,即行号减去1。除非您有超过2019行,否则if
将不会计算为True
相反,您可以查看
line
变量中的行。每个回合都是一个字符串,因此您可以查看它的第一个字符并查看if it is a digit:要将整数起始行和其他行写入2个单独的文件,请打开2个这样的文件,然后根据
if
使用print
进行写入:我们将
end=""
传递给print
以避免额外的新行,因为一个新行来自读取文件的行相关问题 更多 >
编程相关推荐