How to set read and write position in a file in Python?


As a part of file handling operations, in Python, you can carry out the operation of setting the read and write positions within a file to access or modify specific parts of its content. This functionality permits you to navigate and explore through the file performing various operations at desired locations. Through the medium of this article, we will learn to master the operation of setting the read and write positions in a file using Python. You can always follow the descriptive and detailed explanations and code examples given below to understand and gain the skill of positioning within a file.

Setting the Read Position in a File

In order to be able to set the read position within a file, you can use the seek() method. This is how it works:

  • Step 1: You open the file in read mode using the open() function.

  • Step 2: You then assign the returned file object to a variable.

  • Step 3: You start using the seek() method with the desired position as the argument to set the read position.

  • Step 4: You later read the content from the new position using the read() method.

Let us follow a code snippet that simply explains the process:

Example

Suppose we have a text file as shown below

#myfile.txt
This is a test file

# Open the file in read mode
file = open('myfile.txt', 'r')

# Set the read position to the desired location (e.g., 10th character)
file.seek(10)

# Read the content from the new position
content = file.read()

# Print the content
print("Content:", content)

# Close the file
file.close()

When the above code is run, the myfile.txt when opened shows the following content.

Output

Content: e test file

Setting the Write Position in a File

Let us learn how to set the 'write' position within a file; here is how you can follow these steps:

  • Step 1: You start by opening the file in write mode using the open() function.

  • Step 2: You then assign the returned file object to a variable.

  • Step 3: You next make use of the seek() method with the desired position as the argument to set the 'write' position.

  • Step 4: Lastly, you can write the desired content using the write() method.

Let us look at an example code snippet:

Example

Suppose we have a text file as shown below

#myfile.txt
This is a test file

Here, the seek() method is called on the file object to set the write position to the specified location in the file. The parameters passed to seek() are 0 (offset) and 2 (whence). The offset parameter 0 means the write position will be set relative to the start of the file. The whence parameter 2 means the write position will be set at the end of the file.

Hence, file.seek(0, 2) sets the write position to the end of the file.

# Open the file in write mode
file = open('myfile.txt', 'w')

# Set the write position to the desired location (e.g., at the end of the file)
file.seek(0, 2)

# Write new content at the write position
file.write("This is new content.")
# Close the file
file.close()

When above code is run, the myfile.txt when opened shows the following

Output

This is new content.

Combining Read and Write Positions

It is possible that you can also combine read and write positions within a file. Let us look at an example that demonstrates this:

Example

Suppose we have a text file as shown below

#myfile.txt
This is a test file

# Open the file in read and write mode
file = open('myfile.txt', 'r+')

# Set the read position to the desired location (e.g., 5th character)
file.seek(5)

# Read the content from the new position
content = file.read()
print("Content:", content)

# Set the write position to a new location (e.g., 15th character)
file.seek(15)
# Write new content at the write position
file.write("New content")
# Close the file
file.close()

When the above code is run, the myfile.txt when opened shows the following content.

Output

Content: is a test file

Setting Read and Write Positions with tell()

There is always another way to set the read and write positions within a file; like by using the tell() method to determine the current position and then using the seek() method to move to the desired position. Let us learn how you can do it:

  • Step 1: You start by opening the file in the desired mode (r for read, w for write, or a for append) and using the open() function.

  • Step 2: You go on to assign the returned file object to a variable.

  • Step 3: You next use the tell() method to get the current position within the file and store it in a variable.

  • Step 4: You move on to use the seek() method with the desired position as the argument to set the read or write position.

  • Step 5: At the very end, you perform the desired operations at the new position.

Let us look at an example code snippet:

Example

Suppose we have a text file as shown below

#myfile.txt
This is a test file

# Open the file in read mode
file = open('myfile.txt', 'r')

# Get the current read position
position = file.tell()

# Set the read position to the desired location (e.g., 12th character)
file.seek(12)

# Read the content from the new position
content = file.read()

# Print the content
print("Content:", content)

# Close the file
file.close()

When the above code is run, the myfile.txt when opened shows the following content.

Output

Content: st file

Setting Read and Write Positions with Offset

It must be known that, you can also set the read and write positions by providing an offset value to the seek() method. This offset points to the number of bytes to move forward or backward from the current position. Let us look at an example:

Example

Here, we use the seek() method with an offset of 5 and the value 1 to indicate moving forward from the current position. This permits us to set the write position 5 bytes ahead from the current position and write new content at that location.

Suppose we have a text file as shown below

#myfile.txt
This is a test file

# Open the file in write mode
file = open('myfile.txt', 'w')

# Set the write position to the desired location (e.g., move 5 bytes forward from the current position)
file.seek(5, 0)

# Write new content at the write position
file.write("New content")

# Close the file
file.close()

When the above code is run, the myfile.txt when opened shows the following content.

Output

New content

The file handling operation or task of setting the read and write positions within a file makes it possible for you to access specific parts of the content and modify it as needed. Through this article, we have covered and discussed some examples that illustrated how to set the read and write positions in a file using the seek() method. We also introduced some additional examples that demonstrated using tell() method and providing an offset to the seek() method so as to set the read and write positions within a file, in Python. By following diligently and practicing the same easy-to-follow explanations and code snippets, you can gain a sound and solid understanding of positioning within a file in Python. It must be ensured that closing the file after performing operations is done so as to ensure proper handling of system resources.

Updated on: 13-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements