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

Time:11-18

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.

CodePudding user response:

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 

CodePudding user response:

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
  • Related