Setting file offsets in Python


In Python, file offsets can be set using the seek() method of the file object. The seek() method takes two arguments: offset and whence.

The offset argument specifies the number of bytes to move the file pointer. If offset is positive, the file pointer is moved forward; if offset is negative, the file pointer is moved backward.

The whence argument specifies the reference point from which the offset is calculated. There are three possible values for whence:

  • 0 (default): offset is relative to the beginning of the file
  • 1: offset is relative to the current position of the file pointer
  • 2: offset is relative to the end of the file

Here are some examples of how to set file offsets in Python:

# Open a file for reading
f = open('myfile.txt', 'r')

# Set the file pointer to the beginning of the file
f.seek(0)

# Read the first line of the file
line1 = f.readline()

# Set the file pointer to the beginning of the second line
f.seek(len(line1))

# Read the second line of the file
line2 = f.readline()

# Set the file pointer to the end of the file
f.seek(0, 2)

# Write a new line to the end of the file
f.write('\nThis is a new line.')

# Close the file
f.close()

In this example, we open a file for reading and use the seek() method to set the file pointer to different positions in the file. We read lines from the file using the readline() method and write a new line to the end of the file using the write() method. Finally, we close the file using the close() method.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.