""" Test to analyze file.seek positional errors. Feel free to play with different file formats, just pass it as a file object to the functions. """ # Pass in file object from external file def seekread(file): f = open(file, 'rb') # Read entire file f.read() # You can seek within the limit. Negative results will fail! print '--Result of read--' pos1 = f.tell() print 'File position:', pos1, '<-- read limit' # Seek backwards seek_back = 4096 f.seek(-seek_back, 1) pos2 = f.tell() print 'New position: ', pos2 if pos2 == pos1 - seek_back: print 'Correct position!' else: print 'Wrong position' f.close() def seekreadline(file): # Now for processing readline() f = open(file, 'rb') # readline() produces incorrect file position! # Change to readlines() and it will pass! f.readline() print '--- Result of readline() ---' pos1 = f.tell() print 'File position: ', pos1, '<--current position' seek_back = 0 f.seek(-seek_back, 1) pos2 = f.tell() print 'New position in file: ', pos2 if pos2 == pos1 - seek_back: print 'Correct position' else: print 'Wrong position' f.close() def seekboth(file): # Now for processing readline() f = open(file, 'rb') f.read() posread = f.tell() f.readline() print '--- Result of both() ---' pos1 = f.tell() print 'File position from read(): ', posread print 'File position from readline(): ', pos1 seek_back = 4100 f.seek(-seek_back, 1) pos2 = f.tell() print 'New position in file: ', pos2 if pos2 == pos1 - seek_back: print 'Correct position' else: print 'Wrong position' f.close() # generate file file = open("test.log", "wb") file.write("."*100 + "\n" + "."*4100 + "\n" + "."*100) file.close() # Run tests seekread('test.log') # pass seekreadline('test.log') # Fail seekboth('test.log') # Pass