Arvind T
Arvind T

Reputation: 165

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

I am trying to take an input from user and search for the string from a file and then print the line. When I try to execute I keep getting this error. My code is

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)

Upvotes: 1

Views: 44542

Answers (2)

AgnosticDev
AgnosticDev

Reputation: 1853

One of the issues looks to be with calling readline() on the data that is returned from your opened file. Another way to approach this would be:

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")

One thing that I forgot to mention is that I tested this code with Python 2.7 and it looks like you are using Python 3.* because of the use of input() and not raw_input() for STDIN.

In your example, please use:

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

For Python 3.*

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11144

There are many things to improve in your code.

  • data is a string, and str has no attribute readline().
  • read will read the whole content from file. Don't do this.
  • break the loop once you find zinput.
  • don't forget to close the file, when you are done.

The algorithm is really simple:

1) file object is an iterable, read it line by line.

2) If a line contains your zinput, print it.

Code:

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()

Optionally, you can use with to make things easier and shorter. It will close the file for you.

Code:

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

Upvotes: 6

Related Questions