[Tutor] saving output data in a file

spir denis.spir at gmail.com
Fri Dec 4 08:50:55 CET 2009


Prasad Mehendale <prachit915 at gmail.com> dixit:

> I am a beginner. I want to save the output data of the following programme in 
> a file through the programme. Please suggest me the way. I am using Python 
> 2.3.3 on mandrake linux 10 and using "Idle" to save the output to a file 
> presently. 
> Thanks in advance.

You just need to create/open a file before the loop and add a writing instruction -- see below lines inserted in your code.
> #programme to calculate various parameters for a dc-generator.
> import math
> #import os
> #flux is assumed to be .005Wb, and A=parallel paths = 2 for wave winding
> polerpm=[]
> for ConductorsPerSlot in range(1,11):
>     """ we consider that output voltage is 20 V DC """
>     PoleRpmProduct=20000/ConductorsPerSlot
>     polerpm.append(PoleRpmProduct)
> print '(Pole*RPM) product for various values of conductors/slot is: \n', 
> polerpm

  savefile = file("save_file_path", 'w')	###
> for poles in range(2,18,2):
>     print
>     print '\n For number of poles='+str(poles) +'  RPM values are: '
>     for i in range(len(polerpm)):
>                    rpm=polerpm[i]/poles
>                    print rpm,
                     savefile.write(rpm)	###
  savefile.close()				###


Search for file in online or local documentation.

Notes:
* Always close a file if ever...
* open() and file() are aliases.
* The 'w' argument stands for 'writing'.

Another approach is to redirect sys.stdout to a file. Search for this in the doc. The disadvantages imo are (1) this is less obvious (redirection can easily be overlooked) and (2) you lose output to console for checking.

Denis

Denis
________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list