AttributeError:'str'对象在尝试搜索字符串并打印该行时没有属性'readline'

时间:2017-05-03 10:49:59

标签: python input readline

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

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)

2 个答案:

答案 0 :(得分:3)

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

  • 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

答案 1 :(得分:0)

对于从打开的文件返回的数据调用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。*