【问题标题】:View one specific project using its ID使用其 ID 查看一个特定项目
【发布时间】:2021-11-10 09:25:29
【问题描述】:

我想搜索文件中的 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

【问题讨论】:

    标签: python file-handling


    【解决方案1】:

    可以使用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-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2020-09-12
      相关资源
      最近更新 更多