【问题标题】:How to get script to read file, accept user input, and display specific line from user input如何获取脚本以读取文件、接受用户输入并显示来自用户输入的特定行
【发布时间】:2021-01-01 12:46:18
【问题描述】:

我正在尝试编写此代码,以便用户被询问要搜索哪一行,然后他们输入它,然后您显示用户想要的行。

    import os

    f = open("input_file_lab_1.txt","r")
    allData = f.read()#3

    cleanedData = allData.split("\n")
    name = input("enter line to search\n").strip()
   
    n = 0
    while n == 0:
    for line in range(len(cleanedData)): 
        if name in cleanedData[line]: 
            print(name) 
            n = 1
        else:
            pass
    
    f.close()

不确定是否有更简单的方法。我也不断收到错误

  File "os1.py", line 7, in <module>

  name = input("enter line to search\n").strip()#5

AttributeError: 'int' object has no attribute 'strip'

【问题讨论】:

  • 你确定你使用的是 Python 3 吗?
  • 我刚刚看到我使用的第一个错误我没有将它作为 python3 运行,但它仍然不起作用
  • 您在使用 Python 3 时仍然遇到同样的错误吗?
  • 看上面,代码没有正确缩进。请发布您正在运行的确切代码。
  • 不,它让我输入用户输入,我尝试使用数字 1,然后它只是输出了一堆 1

标签: python python-3.x file input kali-linux


【解决方案1】:

你可以使用这个sn-p:

import os

with open("input.txt","r") as f:
    name = input("enter line to search\n").strip()
    for line in f:
        if name in line:
            print(line)
            break

编辑:使用with statement 而不是@alec_djinn 建议的f.open()/close()

【讨论】:

  • @nicole yw。仅供参考:如果您想说“谢谢”,您可以接受答案,不要写“谢谢”之类的评论。它来自堆栈溢出帮助中心。阅读更多:stackoverflow.com/help/someone-answers
  • 我建议使用with statement 而不是f.open()/close(),这是首选方式。
【解决方案2】:

你可能想试试python的标准库

https://docs.python.org/3/library/linecache.html#module-linecache

import linecache
lineNumber = input("enter line to search\n").strip()
line = linecache.getline(fileName, lineNumber)
print(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多