How to check if a specific number is present in the lines of a file?

Question:

I have a file named in.txt.

in.txt

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

i need to check if number 20 is present in file and if present i need the output to look like this.

Expected output:

out.txt

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

this is my current attempt:

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")

this is current output:
out.txt

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

this is because it is checking "20" in every line but i only need to check the last column.

Asked By: V_S

||

Answers:

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'}" )

output:

0020fb435  00000326fab123bc2a 20 twenty_number
00003b4c6  0020346afeff655423 26 none
0000cb341  be3652a120fffcabd5 26 none
Answered By: amirhm

You just need to use endswith as the if condition.

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")

output in out.txt

0000fb435  00000326fab123bc2a 20 twenty_number 
00003b4c6  0020346afeff655423 26 none 
0000cb341  be3652a156fffcabd5 26 none 
Answered By: Chandler Bong
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.