[Tutor] reading sequencies from text file

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Aug 5 14:43:01 CEST 2004


> I want to write always like
>
> while (seq=fread(f, 4340))
> { fwrite(....);
> }

> while 1:
>     actline = f.read(4340)
>     if len(actline) == 4340:
>         e.write(actline[:70])
>         e.write('\n')
>     else: break

> Is it the pythonic way?

Pretty much although usually the break is put inside the if, like
this:

while 1:
     actline = f.read(4340)
     if len(actline) < 4340:
         break
     e.write(actline[:70])
     e.write('\n')


Which avoids an extra level of structural complexity for the mainline
code.

Another way closer to your prefered route is to create a File class
that
reads the data into a buffer. Somewhat like:

class File:
    def __init__(self,name,mode='r'):
         self.f = open(name,mode)
    def read(self,size=0):
         self.buffer = self.f.read(size)
         return len(self.buffer)
    etc....

f = File('foo.txt')
while f.read(4340) == 4340:
      # do stuff with f.buffer

If you do that kind of file processing often you might find the effort
of creating it in a module worthwhile.

HTH,

Alan G.



More information about the Tutor mailing list