Python 属性错误:';str';对象没有属性';readline';在尝试搜索字符串并打印行时
我试图从用户那里获取输入,从文件中搜索字符串,然后打印行。当我尝试执行时,我不断地得到这个错误。我的代码是Python 属性错误:';str';对象没有属性';readline';在尝试搜索字符串并打印行时,python,input,readline,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) 代码中有许多地方需要改进 data是一个
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
找到
后,中断循环zinput
- 完成后,别忘了关闭文件李>
zinput
,请打印它
代码:
或者,您可以将与
一起使用,使事情变得更简单、更短。它将为您关闭该文件
代码:
代码中有许多地方需要改进
是一个字符串,data
没有属性str
李>readline()
将从文件中读取全部内容。不要这样做read
找到
后,中断循环zinput
- 完成后,别忘了关闭文件李>
zinput
,请打印它
代码:
或者,您可以将与
一起使用,使事情变得更简单、更短。它将为您关闭该文件
代码:
对打开的文件返回的数据调用
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")
我忘记提到的一件事是,我用Python2.7测试了这段代码,看起来您使用的是Python3.*因为STDIN使用了input()而不是raw_input()
在您的示例中,请使用:
zInput = str(input("Enter the word you want me to search: "))
对于Python 3.*问题之一似乎是对打开的文件返回的数据调用
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")
我忘记提到的一件事是,我用Python2.7测试了这段代码,看起来您使用的是Python3.*因为STDIN使用了input()而不是raw_input()
在您的示例中,请使用:
zInput = str(input("Enter the word you want me to search: "))
对于Python 3.*您的代码在很多方面都是错误的。您从文件中读取了
read()
,然后在循环中使用了readline()
,这基本上覆盖了用户输入。然后您用数据中的每一行覆盖了输入调用中的zinput
。您的代码在很多方面都是错误的。您从文件中读取了read()
,然后在循环中使用了readline()
,这基本上覆盖了用户输入。然后您用数据中的每一行覆盖了输入调用中的zinput
。您还可以使用with
向他显示文件处理。您还可以使用with
向他显示文件处理