""" 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) posread = f.tell() # Seek backwards seek_back = back f.seek(-seek_back, 1) pos2 = f.tell() f.close() # Print results print '\n--Result of read--\n' print 'File position:\t\t\t%4d' % posread print 'Amount to seek back:\t\t%4d' % -back print 'New position:\t\t\t%4d' % pos2 # Calculate and print if pos2 == posread - seek_back: print 'Correct position!\n\n' else: print 'Wrong position\n\n' def seekreadline(file, size, back): # Now for processing readline() f = open(file, 'rb') f.readline(size) posline = f.tell() seek_back = back f.seek(-seek_back, 1) pos2 = f.tell() f.close() print '--- Result of readline() ---\n' print 'File position:\t\t\t%4d' % posline print 'Amount to seek back:\t\t%4d' % -seek_back print 'New position in file:\t\t%4d' % pos2 if pos2 == posline - seek_back: print 'Correct position\n\n' else: print 'Wrong position\n\n' def seekboth(file, size, back): # Now for processing readline() f = open(file, 'rb') f.read(size) posread = f.tell() f.readline() posline = f.tell() seek_back = back f.seek(-seek_back, 1) pos2 = f.tell() # Print result print '--- Result of both() ---\n' print 'File position from read():\t\t%4d' % posread print 'File position from readline():\t\t%4d' % posline print 'Amount to seek back:\t\t\t%4d' % -seek_back print 'New position in file:\t\t\t%4d' % pos2 # Calculate if pos2 == posline - seek_back: print 'Correct position\n\n' else: print 'Wrong position\n\n' def seekboth_reversed(file, size, back): # Now for processing readline() f = open(file, 'rb') f.readline() posline = f.tell() f.read(size) posread = f.tell() seek_back = back f.seek(-seek_back, 1) pos2 = f.tell() f.close() print '--- Result of both_reversed() ---\n' print 'File position from readline():\t\t%4d' % posline print 'File position from read():\t\t%4d' % posread print 'Amount to seek back:\t\t\t%4d' % -seek_back print 'New position in file:\t\t\t%4d' % pos2 if pos2 == posread - seek_back: print 'Correct position\n\n' else: print 'Wrong position\n\n' # 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, 100) # Pass seekboth_reversed('test.log', 1024, 100)