简体   繁体   中英

Print first line in python stdout

I have a file with contents in the following format, the values are sperated by ";"

abc@test;value1;12345;value1.1
nmp@test;value2;98766;value2.1
plm@test;value1;12345;value1.1

I am working on a python script to print the value if line matches the input provided. In this, if the input value is "12345", the output will be as follows:-

abc@test;value1;12345;value1.1
plm@test;value1;12345;value1.1

what I need is only the first line from the output. Below is the code:-

with open (full_file,'r') as f:
    for line in f:
        if input_id in line:            
           print (line)

To split the value (columns), I found to use line.split(";")[2] in this case.

How to get only the 1st line/row from the output?

There are couple of ways to do this,

You can break from the loop as soon as you found the match,

result = None
with open (full_file,'r') as f:
    for line in f:
        if input_id in line:    
           result = line
           break

Later you can check

if result is None:
   print("No Match found")
else:
   print(f"Match found {result}")

OR

You can use generator expression,

with open (full_file,'r') as f:
    result = next(line for line in f if input_id in line, None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM