0

我想搜索文件内的 id 并输出它的其他信息。目前这是我的代码

with open("Inputdetails.txt", "r") as file:
            pick = input("Enter id: ")
            for line in file:
                if pick in line:
                    print(line)

我的文本文件如下所示:

Id: 1
Title: ExampleTitle
Size: 50
Priority: 1

Id: 2
Title: Example Title2
Size: 50
Priority: 2

我想搜索它的Id并显示相关内容。例 1:

  Enter a number to search: 1

输出将是:

  Id: 1
  Title: ExampleTitle
  Size: 50
  Priority: 1
4

1 回答 1

0

你可以使用Python File 的 next() 方法

Python 文件方法 next() 用于将文件用作迭代器时,通常在循环中,重复调用 next() 方法。此方法返回下一个输入行,或在 EOF 被命中时引发 StopIteration。

print('Enter id:')
id = input()
InputText = 'Id: ' + id
with open('C:/Users/user/Desktop/test.txt') as f:
    for line in f:
        if InputText in line:
            print(line)
            for i in range(3):
                print(next(f))

在此处输入图像描述

于 2021-11-10T10:01:53.223 回答