1

I had a line of Python code that produced what I wanted. The code was:

os.system('cat {0}|egrep {1} > file.txt' .format(full,epoch))

and produced a file with the following contents:

3                321.000 53420.7046629965511    0.299                 0.00000
3                325.000 53420.7046629860714    0.270                 0.00000
3                329.000 53420.7046629846442    0.334                 0.00000
3                333.000 53420.7046629918374    0.280                 0.00000

I then just wanted to adjust the code so that is said "TEXT 1" at the top, so I tried the first thing that came into my head, and I changed the code to:

h = open('file.txt','w')
h.write('MODE 2\n')
os.system('cat {0}|egrep {1} > file.txt' .format(full,epoch))

When I do this, I get the output:

TEXT 1
   317.000 54519.6975201839344    0.627                 0.00000
3                321.000 54519.6975202038578    0.655                 0.00000
3                325.000 54519.6975201934045    0.608                 0.00000
3                329.000 54519.6975201919911    0.612                 0.00000

i.e. the first line after "TEXT 1" is not right, and is missing the first "3". Can anyone tell me what I am doing wrong, and possibly a better way to do this simple task.

Thank you.

miku
  • 181,842
  • 47
  • 306
  • 310
user1551817
  • 6,693
  • 22
  • 72
  • 109
  • 1
    Check this post: http://stackoverflow.com/questions/4454298/prepend-a-line-to-an-existing-file-in-python – hek2mgl Apr 25 '13 at 22:57

2 Answers2

2

You can call grep your way, or you can use subprocess.call(), which is my preferred method.

Method 1: use os.system()

os.system('echo TEXT 1 >file.txt; egrep {1} {0} >> file.txt'.format(full, epoch))

This method will prepend TEXT 1 before invoking egrep. Note that you don't need cat.

Method 2: use subprocess.call()

with open('out.txt', 'wb') as output_file:
    output_file.write('TEXT 1\n')
    output_file.flush()
    subprocess.call(['egrep', epoch, full], stdout=output_file)

This is my preferred method for several reasons: you have more control over the output file such as the ability to handle exception in case open failed.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
1

You open a file handle with python, write to it, but Python leaves it to the OS to do the flushing, etc. - by design, if want something to be written to file before something else gets written, you'll need to flush it manually (in fact, you'll need to flush and fsync).

Another note: The > file.txt creates a new file, while you might want to append - which would be written as >> file.txt. In short: your code might be more indeterministic as you think.

Another way to do it, since you are already on the shell level is to use the subprocess module:

from subprocess import call

sts = call("echo 'TEXT 1' > file.txt", shell=True)
sts = call("cat {0}|egrep {1} >> file.txt".format(full,epoch), shell=True)
miku
  • 181,842
  • 47
  • 306
  • 310