[Tutor] how to read from a txt file

Alan Gauld alan.gauld at freenet.co.uk
Wed Mar 30 22:38:47 CEST 2005


> please help me!

I'll try but I m9issed the early bit of this thread so jumping in
cold...

> > > so that i can read the text file created by this:
> > >
> > > self.filename = "%s\%s.txt"

If the OS is Windows you might want to use two \\ just to be safe
or alternatively use a forward slash instead.


> > >
%(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H
%M"))
> > >
> > > self.table_file = open(self.filename,"a")
> > > self.table_file.write('%f\t'%self.temp11)
> > > self.table_file.write('%f\t'%self.temp22)
> > > self.table_file.write('%f\t'%self.pyra11)
> > > self.table_file.write('%f\t'%self.pyra22)
> > > self.table_file.write('%f\t'%self.voltage11)
> > > self.table_file.write('%f\t'%self.current11)
> > > self.table_file.write('\n')

All of that is on a single line, so you could do it with a single
format string
if you prefer.

self.table_file.write('%f\t%f\t%f\t%f\t%f\t%f\n' %
                       self.temp11,self.temp22,
                       self.pyra11,self.pyra22,
                       self.voltage11,self.current11)

Personally I find it easier to read.

To read it back you want to read the line, strip it and then split it
using
a tab as separator.

self.data = tuple(inputfile.readline().strip().split('\t'))
( self.temp11,    self.temp22,
  self.pyra11,    self.pyra22,
  self.voltage11, self.current11 ) = self.data



HTH,

Alan G.



More information about the Tutor mailing list