AttributeError: 'str' object has no attribute 'readline' while trying to search for a string and print the line

AttributeError: 'str' object has no attribute 'readline' while trying to search for a string and print the line

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

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)

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

  • 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

其中一个问题似乎与调用 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.* 因为使用了 input() 而不是raw_input() 用于标准输入。

在您的示例中,请使用:

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

对于Python 3.*