Search code examples
pythonpython-2.6

Calling grep after writing to file Python 2.6.4 os.system


I'm trying to read from text.txt, write certain lines to temp.txt, then using os.system call grep on temp.txt After I run the program, temp.txt gets created and I can call the same grep command in terminal to get my desired results which makes me think this is an asynchronous problem

I'm using Python 2.6.4

import os

#opens new file to write to
temp = open("temp.txt", "w+")

boolStart = False
with open("text.txt", "r") as text:
    for line in text:
        if("GREEN" in line):
            boolStart = True
        elif("YELLOW" in line):
            boolStart = False
        if(boolStart):
            temp.write(line)
            

os.system("grep -e 'Ace: ' -e 'Spade' {0}".format("temp.txt"))

I get nothing back from running python script.py even if I pipe to a new file

Question: Why aren't I able to call grep on a file I just wrote in the same program

For context this is text.txt

******************************
*************RED**************
******************************

Ace: John
Ace: Mike
Spade: Nick
Spade: Pete

******************************
***********GREEN**************
******************************

Ace: Emily
Ace: Anna
Spade: Krista
Spade: Maddie

******************************
*************YELLOW***********
******************************

Ace: Nicole
Ace: Scott
Ace: Zac
Ace: Phil

And this is temp.txt the file I'm trying to call grep on

***********GREEN**************
******************************

Ace: Emily
Ace: Anna
Spade: Krista
Spade: Maddie

******************************

Solution

  • The problem is that you forgot to .close() the file, which may leave buffered data which has yet to be written to disk.

    However, there is no need to use grep or write the data to a temporary file.

    for line in text:
        # ...
        if BoolStart:
            if 'Ace:' in line or 'Spade:' in line:
                print(line)