write a .txt file

Cameron Simpson cs at zip.com.au
Tue Jul 13 02:16:29 EDT 2010


On 12Jul2010 21:28, Jia Hu <hujia06 at gmail.com> wrote:
| I have a problem about how to generate a specific.txt file. I use the
| following code:
| 
| #!/usr/bin/python
| # OS: Ubuntu
| import subprocess
| fileName = open ('final.txt', 'a')
| fileName.write ('%s %s %s \n' % (12,25,9))

String still in Python's buffer, not yet in the file. Add:

  fileName.flush()

to ensure data in file before running echo.

| desLrr = subprocess.Popen('echo "hello" >> final.txt ', shell=True)

Command dispatched, but not yet waited for. So your Python program proceeds
and writes to the file _before_ the echo command gets to run.

Wait for desLrr to complete before proceeding.

| fileName.seek(0,2)
| fileName.write ('%s %s %s \n' % (85,25,12))
| fileName.close()

And the rest is ok.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

We tend to overestimate the short-term impact of technological change and
underestimate its long-term impact.     - Amara's Law



More information about the Python-list mailing list