write a .txt file

MRAB python at mrabarnett.plus.com
Mon Jul 12 21:58:31 EDT 2010


Jia Hu wrote:
> Hello:
>  
> 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))
> desLrr = subprocess.Popen('echo "hello" >> final.txt ', shell=True)
> 
> fileName.seek(0,2)
> fileName.write ('%s %s %s \n' % (85,25,12))
> fileName.close()
>  
> The above code generates the following result:
> 12 25 9
> 85 25 12
> hello
>  
> What I want is:
> 12 25 9
> hello
> 85 25 12
>  
> Could someone provies some suggestions about this problem?
>  
> Thank you.
> 
When "echo" is called the file is still open, so the might not be able
to write to it. Try closing the file before starting the subprocess and
then reopen it afterwards.

By the way, it slightly confusing that you call the variable "fileName",
but it doesn't contain the name of a file! :-)



More information about the Python-list mailing list