How can I use grep in Python?

0 votes

There is a file (query.txt) which has some keywords/phrases which are to be matched with other files using grep. The last three lines of the following code are working perfectly but when the same command is used inside the while loop it goes into an infinite loop or something(ie doesn't respond).

import os

while b:
    cmd='grep %s my2.txt'%b    #my2 is the file in which we are looking for b

a='He is'
cmd='grep %s my2.txt'%a
Dec 12, 2018 in Python by ariaholic
• 7,340 points

1 answer to this question.

0 votes

First of all, you are not iterating over the file properly. You can simply use for b in f: without the .readline() stuff.

Then your code will blow in your face as soon as the filename contains any characters which have a special meaning in the shell. Use instead of os.system() and pass an argument list.

Here's a fixed version:

import os
import subprocess
with open('query.txt', 'r') as f:
    for line in f:
        line = line.rstrip() # remove trailing whitespace such as '\n'['/bin/grep', line, 'my2.txt'])

However, you can improve your code even more by not calling grep at all. Read my2.txt to a string instead and then use the re module to perform the search. In case you do not need a regex at all, you can even simply use if line in my2_content

answered Dec 12, 2018 by charlie_brown
• 7,720 points

Related Questions In Python

0 votes
1 answer

How can I use indices in math using python

Operator ^ is a bitwise operator, which does "bitwise exclusive or". More: The ...READ MORE

answered Dec 11, 2018 in Python by ariaholic
• 7,340 points
0 votes
1 answer

How can I make use of getopt or optarg in Python?

Hi, I was asked this by one ...READ MORE

answered Feb 8 in Python by Nymeria
• 3,520 points
0 votes
0 answers

where and how can i use PYTHONPATH in python?

is there a particular syntax for this?? READ MORE

Apr 8 in Python by Waseem
• 4,480 points
0 votes
1 answer

How can I use the power function in python 2.7?

print(pow(3,4)) #this will return the exponentiation of 3 ...READ MORE

answered May 20 in Python by Mohammad
• 3,170 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 405 views
+4 votes
6 answers
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,720 points
0 votes
1 answer

How can I compare the content of two files in Python?

Assuming that your file unique.txt just contains ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points