Gnibbler'ın en çok oylanan cevabına göre (20 Kasım '09, 0:27): bu sınıf, dosya nesnesine head () ve tail () yöntemini ekler.
class File(file):
def head(self, lines_2find=1):
self.seek(0)
return [self.next() for x in xrange(lines_2find)]
def tail(self, lines_2find=1):
self.seek(0, 2)
bytes_in_file = self.tell()
lines_found, total_bytes_scanned = 0, 0
while (lines_2find+1 > lines_found and
bytes_in_file > total_bytes_scanned):
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
self.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += self.read(1024).count('\n')
self.seek(-total_bytes_scanned, 2)
line_list = list(self.readlines())
return line_list[-lines_2find:]
Kullanım:
f = File('path/to/file', 'r')
f.head(3)
f.tail(3)