views:

324

answers:

1

In python I am trying to write a script that will edit text files and then run executables that use those text files. It basically entails 1)opening and reading/writing to a text file, and 2)using the file I just wrote in a bash command. Here is a simple example:

import subprocess

# write file
a = ['1\n','2\n','3\n','4\n','5th and final line']
f = open('junk01.txt', 'wb')
f.writelines(a)
f.close

# show file
subprocess.call('cat junk01.txt', shell=True)

For some reason on that subprocess.call command it is not showing the contents of the junk01.txt file. However after I run this code and type cat junk01.txt in bash the file has been written properly. Similarly, I'm finding that after I open, write to, and close a text file and then try to use it in an executable, the file hasn't been written to yet. Any explanation on why this is and what I can do to fix it?

+8  A: 

Close the file by actually calling the close() method. This will implicitly flush the buffers to disk.

f.close()

rather than

f.close     #this probably doesn't do anything, but if there was no close method it would raise an error.
Joe Koberg
Is that all my problem was? Wow, I feel like an idiot. I gave it a try and sure enough, it works.This is what I get for trying to do something complex in a language I just started learning last week... Thanks!
Forgetting to flush the output has caught me years after I should have "known better" - I have a feeling it's a common error.
Joe Koberg
f.close does do something. I locates the close method function. Doesn't evaluate it, but it at least finds it.
S.Lott