python-3.x 如何检查一个文件的行中是否存在特定的数字?

35g0bw71  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(133)

我有一个名为in.txt的文件。
in.txt

0000fb435  00000326fab123bc2a 20
00003b4c6  0020346afeff655423 26
0000cb341  be3652a156fffcabd5 26
.
.

我需要检查文件中是否存在编号20,如果存在,我需要输出如下所示。

预期输出

out.txt

0020fb435  00000326fab123bc2a 20 twenty_number
00003b4c6  0020346afeff655423 26 none
0000cb341  be3652a120fffcabd5 26 none
.
.

这是我目前尝试:

with open("in.txt", "r") as fin:
    with open("out.txt", "w") as fout:
        for line in fin:
           line = line.strip()
           if '20' in line:
               fout.write(line + f" twenty_number \n")

这是当前输出out.txt

0020fb435  00000326fab123bc2a 20 twenty_number
00003b4c6  0020346afeff655423 26 twenty_number
0000cb341  be3652a120fffcabd5 26 twenty_number
.
.

这是因为它在每一行都检查“20”,但我只需要检查最后一列。

qacovj5a

qacovj5a1#

您只需要使用endswith作为if条件。

with open("in.txt", "r") as fin:
    with open("out.txt", "w") as fout:
        for line in fin:
           line = line.strip()
           if line.endswith('20'):
               fout.write(line + f" twenty_number \n")
           else:
               fout.write(line + f" none \n")

out.txt中的输出

0000fb435  00000326fab123bc2a 20 twenty_number 
00003b4c6  0020346afeff655423 26 none 
0000cb341  be3652a156fffcabd5 26 none
tp5buhyn

tp5buhyn2#

with open("in.txt", "r") as fin:
    with open("out.txt", "w") as fout:
        for line in fin:
            last_col = line.split()[-1]
            fout.write(f"{line.strip()} {'twenty_number' if '20' in last_col else 'none'}" )

输出:

0020fb435  00000326fab123bc2a 20 twenty_number
00003b4c6  0020346afeff655423 26 none
0000cb341  be3652a120fffcabd5 26 none

相关问题