【问题标题】:AttributeError: 'str' object has no attribute 'readline' while trying to search for a string and print the lineAttributeError:“str”对象在尝试搜索字符串并打印该行时没有属性“readline”
【发布时间】:2017-05-03 10:49:59
【问题描述】:

我正在尝试从用户那里获取输入并从文件中搜索字符串,然后打印该行。当我尝试执行时,我不断收到此错误。我的代码是

file = open("file.txt", 'r')
data = file.read()
zinput = str(input("Enter the word you want me to search: "))
for zinput in data:
    line = data.readline()
    print (line)

【问题讨论】:

  • 你的代码在很多层面都是错误的。您从文件中执行了read(),然后在循环中使用readline(),这基本上会覆盖用户输入。
  • 然后用数据中的每一行覆盖输入调用中的zinput

标签: python input readline


【解决方案1】:

您的代码中有很多地方需要改进。

  • data 是一个字符串,str 没有属性readline()
  • read 将从文件中读取全部内容。不要这样做。
  • break 找到zinput 后循环。
  • 完成后不要忘记关闭文件。

算法真的很简单:

1) 文件对象是可迭代的,逐行读取。

2) 如果一行包含您的zinput,请打印它。

代码:

file = open("file.txt", 'r')
zinput = str(input("Enter the word you want me to search: "))
for line in file:
    if zinput in line:
        print line
        break
file.close()

(可选)您可以使用with 使事情变得更轻松、更短。它将为您关闭文件。

代码:

zinput = str(input("Enter the word you want me to search: "))
with open("file.txt", 'r') as file:
    for line in file:    
        if zinput in line:
            print line
            break

【讨论】:

  • 你也可以使用with向他展示文件处理
【解决方案2】:

其中一个问题似乎是对从您打开的文件返回的数据调用readline()。另一种解决方法是:

flag = True
zInput = ""
while flag:
    zInput = str(raw_input("Enter the word you want me to search: "))
    if len(zInput) > 0:
        flag = False
    else: 
        print("Not a valid input, please try again")

with open("file.txt", 'r') as fileObj:
    fileString = fileObj.read()
    if len(fileString) > 0 and fileString == zInput:
        print("You have found a matching phrase")

我忘记提及的一件事是,我使用 Python 2.7 测试了这段代码,看起来您使用的是 Python 3.*,因为 STDIN 使用了 input() 而不是 raw_input()。

在您的示例中,请使用:

zInput = str(input("Enter the word you want me to search: "))

对于 Python 3.*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多