Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading