perl chomp equivalent in python?
Alex
alex at somewhere.round.here
Thu Feb 10 00:01:16 EST 2000
> It'd be kinda cool if readlines() could take an argument that meant to
> strip away any trailing whitespace.
Hi, Will.
Below are some classes I often use for that sort of thing.
Alex.
class lazy_file:
def __init__ (self,filename, print_count_period=None,
sizehint=10**7, mode='r', open=open):
self.file = open (filename, mode)
self.line_count=0
self.sizehint = sizehint
self.print_count_period = print_count_period
self.buffer = None
def readline (self):
if not self.buffer:
self.buffer = self.file.readlines (self.sizehint)
if not self.buffer:
self.line = ''
else:
self.line = self.buffer.pop (0)
if self.line [-1] == '\n':
self.line = self.line [: -1]
if self.print_count_period and \
not (self.line_count % self.print_count_period):
print self.line_count
self.line_count=self.line_count+1
return self.line
class File_loop:
def __init__ (self, filename, print_count_period=None,
sizehint=10**7, mode='r', open=open):
self.file = lazy_file(filename, print_count_period,
sizehint, mode, open)
def __getitem__(self,index):
if self.file.readline():
return self.file.line
else:
raise IndexError, 'File finished'
if __name__ == '__main__':
f = File_loop ('/data/databases/gbpri/introns.txt')
for l in f:
print l[-10:]
More information about the Python-list
mailing list