[Tutor] [Fwd: Re: Problems writing data into a file]

Stefan Heyne stefan.heyne at epfl.ch
Mon Dec 18 09:50:16 CET 2006


OK, thanks....no I get the data into a file output..but I still am stuck 
with the formatting...
1) there are brackets around the data that are due to the necessary (??) 
conversion to a string
2) I cannot figure out how to insert a newline command....

Here's the code:
g=open('output.txt', 'w')
for x in range(1,226):
   y1=m.extract('TEMP',32, 1131, component='1', cycle=x, subcycle=1)
   y2=m.extract('PRES',32, 1131, component='1', cycle=x, subcycle=1)
   testline = x,y1,y2
   line = str(testline)
   g.write(line)

g.close()

And here an extract of the output:
(1, [458.35813161745779], [112712.77970477825])(2, [457.03731677841921], 
[113061.80332906457])(3, [458.24706379677764], [112931.83711259064])(4, 
[460.89541534790976], [112584.88323863815])

What I would like:
1, [458.35813161745779], [112712.77970477825]
2, [457.03731677841921], [113061.80332906457]
3, [458.24706379677764], [112931.83711259064]
4, [460.89541534790976], [112584.88323863815]
...

Thanks in advance,

 Stefan
-------- Original Message --------
Subject: 	Re: [Tutor] Problems writing data into a file
Date: 	Mon, 18 Dec 2006 02:13:49 -0600
From: 	Luke Paireepinart <rabidpoobear at gmail.com>
To: 	Stefan Heyne <stefan.heyne at epfl.ch>
CC: 	tutor at python.org
References: 	<45864AB4.8070800 at epfl.ch>



> for x in range(1,226):
> #   g=open('output', 'w')
>      y1=m.extract('TEMP',32, 1131, component='1', cycle=x, subcycle=1)
>      y2=m.extract('PRES',32, 1131, component='1', cycle=x, subcycle=1)
> #   testout = (x,y1,y2,'\n')
> #   line = str(testout)
> #   g.write(line)
>      print x,y1,y2
> #   g.close()
>   
You're opening the same file, 'output', 225 times and overwriting the 
contents each time.
the write method of file access erases its previous contents.
you should use a variable for the filename,
I.E.
g = open('output%i' % x, 'w')
which will open output1, output2, output3, etc... for each time through 
the loop,
or you should open the file before the loop begins and only have writes 
inside the loop.
Then you can close the file after the loop exits.

HTH,
-Luke



-- 
************************************************
Stefan Heyne
Laboratoire d'Energétique Industrielle - http://leni.epfl.ch

tél. +41-21-693 3513
fax +41-21-693 3502
email: stefan.heyne at epfl.ch
Bureau: ME A2.394 - http://plan.epfl.ch/index.html?room=mea2394 

Adresse postale:
EPFL, STI-ISE-LENI
ME A2.394 (Bâtiment ME)
Station 9
CH-1015 Lausanne
************************************************



More information about the Tutor mailing list