How to find out where is the file pointer

Find out the position of a file pointer

seek(offset[, whence]) moves the file pointer to the position described by offset and whence. offset is a byte (character) count. whence defaults to 0, which means that the offset is from the beginning of the file. whence may also be set to 1 (move relative to current position: the offset may be negative), or 2 (move relative to the end of the file).


f = open(r'c:\text\somefile.txt', 'w') 
f.write('01234567890123456789') 
f.seek(5) # ww w. ja  v a2 s  . c om
f.write('Hello, World!') 
f.close() 
f = open(r'c:\text\somefile.txt') 
print f.read() 

Move around within the file using seek().


f = open('/tmp/x', 'w+')
print f.tell()# from ww w  .j  a  va  2 s .c  o m
f.write('test line 1\n')         # add 12-char string [0-11]
print f.tell()
print f.write('test line 2\n')   # add 12-char string [12-23]
print f.tell()                   # tell us current file location (end))
print f.seek(-12, 1)             # move back 12 bytes
print f.tell()                   # to beginning of line 2
print f.readline()
print f.seek(0, 0)               # move back to beginning
print f.readline()
print f.tell()                   # back to line 2 again
print f.readline()
print f.tell()                   # at the end again
print f.close()                  # close file

Use tell() function to find out file position

tell() method returns the current file position.


f = open(r'c:\text\somefile.txt', 'w')
f.write('01234567890123456789')
f.seek(5)#   ww w. jav a  2 s.c  o m
f.write('Hello, World!')
f.close()
f = open(r'c:\text\somefile.txt')
print f.read()
f = open(r'c:\text\somefile.txt')
print f.read(3)
print f.read(2)
print f.tell()

Handling I/O Errors

The following code shows how to safely open and read from a file and gracefully handle errors.


try:                                          
   fsock = open(filename, "rb", 0)             
   try: # from   w  ww.j a  v a 2 s.c  om
       fsock.seek(-128, 2)                     
       tagdata = fsock.read(128)               
   finally:                                    
       fsock.close() 
except IOError:                                
    pass 




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module