1

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)
2
  • 1
    Your code is wrong in so many level. You did read() from file and then using readline() in loop which basically overwrites the user input. Commented May 3, 2017 at 10:52
  • And then you overwrite the zinput from the input call with every line in the data. Commented May 3, 2017 at 10:53

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

you can also show him the file handling using with
0

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.*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.