在python标准输出中打印第一行

2024-05-20 01:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下格式内容的文件,其值由“;”

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

我正在编写一个python脚本,以便在行与提供的输入匹配时打印值。在这种情况下,如果输入值为“12345”,则输出如下:-

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

我只需要输出的第一行。代码如下:

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

为了分割值(列),我发现在本例中使用line.split(";")[2]

如何仅从输出中获取第一行/行


Tags: 文件代码intest脚本内容格式with
1条回答
网友
1楼 · 发布于 2024-05-20 01:33:09

有两种方法可以做到这一点

一旦找到匹配项,就可以从循环中break

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

以后你可以查一下

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

可以使用生成器表达式

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

相关问题 更多 >