""" 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, size, back): f = open(file, 'rb') # Read entire file f.read(size) # 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 = back print 'Amount to seek back: ', -back 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, size, back): # Now for processing readline() f = open(file, 'rb') # readline() produces incorrect file position! # Change to readlines() and it will pass! f.readline(size) print '--- Result of readline() ---' pos1 = f.tell() print 'File position: ', pos1, '<-- includes NEWLINE' seek_back = back print 'Amount to seek back: ', -seek_back 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, size, back): # Now for processing readline() f = open(file, 'rb') f.read(size) 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 = back print 'Amount to seek back: ', -seek_back 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', 1024, 200) # pass seekreadline('test.log', 1024, 100) # Fail seekboth('test.log', 1024, 1024) # Pass