Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in Python if string is in a text file and print the line?

What I am trying to do is to check whether this string is found in the text file. If it does, I want it to printout that line, else printout a message.

I have implemented this code so far:

 def check_string(string):

     w = raw_input("Input the English word: ")
        if w in open('example.txt').read():
            for w.readlines():
                print line
        else:
            print('The translation cannot be found!')

I've tried implementing that but I got a syntax error.

It says:

invalid syntax at the line -- for w.readlines():

Any idea on how to go with this line of code?

like image 662
bn60 Avatar asked May 08 '13 03:05

bn60


People also ask

How do you check if string is in a line of a text file Python?

Here is a bit simpler example by using in operator: w = raw_input("Input the English word: ") # For Python 3: use input() instead with open('foo. txt') as f: found = False for line in f: if w in line: # Key line: check if `w` is in the line. print(line) found = True if not found: print('The translation cannot be found!

How do you print a string from a text file in Python?

Open the text file in write mode using open() function. The function returns a file object. Call write() function on the file object, and pass the string to write() function as argument. Once all the writing is done, close the file using close() function.

How do you check if something is in a file in Python?

In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False . Likewise, if you use if isdir() to check whether a certain file exists, the method returns False .

How do you print a file line by line in Python?

Method 2: Read a File Line by Line using readline() It will be efficient when reading a large file because instead of fetching all the data in one go, it fetches line by line. readline() returns the next line of the file which contains a newline character in the end.


2 Answers

You should try something like this:

import re
def check_string():
    #no need to pass arguments to function if you're not using them
    w = raw_input("Input the English word: ")

    #open the file using `with` context manager, it'll automatically close the file for you
    with open("example.txt") as f:
        found = False
        for line in f:  #iterate over the file one line at a time(memory efficient)
            if re.search("\b{0}\b".format(w),line):    #if string found is in current line then print it
                print line
                found = True
        if not found:
            print('The translation cannot be found!')

check_string() #now call the function

If you are searching for exact words instead of just sub-string then I would suggest using regex here.

Example:

>>> import re
>>> strs = "foo bar spamm"
>>> "spam" in strs        
True
>>> bool(re.search("\b{0}\b".format("spam"),strs))
False
like image 146
Ashwini Chaudhary Avatar answered Oct 05 '22 23:10

Ashwini Chaudhary


Here is a bit simpler example by using in operator:

w = raw_input("Input the English word: ") # For Python 3: use input() instead
with open('foo.txt') as f:
    found = False
    for line in f:
        if w in line: # Key line: check if `w` is in the line.
            print(line)
            found = True
    if not found:
        print('The translation cannot be found!')

If you'd like to know the position of the string, then you can use find() instead of in operator.

like image 37
kenorb Avatar answered Oct 06 '22 00:10

kenorb