Python

Python File Seek

Python has several techniques for dealing with files. There are methods to manipulate the file pointer effectively and basic operations like reading and writing to files. You will learn how to utilize the seek() method to relocate the file pointer while reading or writing a file in this article.

The seek() function sets a file pointer’s position, while the tell() function returns the file pointer’s current position. Python’s seek() function changes the file’s current location to the offset. Whence is an optional parameter that defaults to 0 for immediate file placement; other values are 1 for seek relative to the present location and 2 for seek relative to the end of the file. There is no value returned. Any seek() actions will be erased at the next write if the file is opened to append with ‘a’ or ‘a+.’ This method is not of any use if the file is just opened for writing and is in the append mode with ‘a,’ but it is useful for files opened in append mode with read enabled. Only offsets returned by tell() are legal when the file is opened in text mode with ‘t.’ The use of various offsets results in unpredictable behavior. It’s vital to keep in mind that not all file objects can be searched.

The purpose of this article is to teach you how to utilize the seek() method to advance or backward the file cursor from its present position. Learn how to relocate the file pointer to the file’s beginning or end. Learn how to determine the current position of the “filehandle” by moving the file pointer backward from the end of the file. So, let’s begin the tutorial.

Example 1:

Consider the following scenario, in which we are reading the contents of a text file with an offset of 5. This indicates that we will begin reading the file at the 5th character.

https://lh4.googleusercontent.com/xJ5LnLgqY9K9P78ijQB9yVSbptJqCuVPMg3-o6SWs97n5-VpYu_gVIhnmj8Y_RgDC6uCnzbzhq1CaJeHFX3mlNTUz4g6IefWlKtBqrltJVLrrnsZZC2x7k4e0NAQUAXNZg1n93zP

Here, we have opened the file by giving the exact path of it. After that, we read the content from the 5th character using the seek method.

with open(r'D:/Users/Demos/demo.txt', "r") as fp:

fp.seek(5)

print(fp.read())

https://lh6.googleusercontent.com/ZPsqR0Iu8Xy_wJsyo1TQjTCwjZYA0rnpRy3emnOHb8bDGeRLCSxYbueohFa1Oob8d0ACO3dVeODoMbjc6NO4mLW-IDnFSrqMpr3IO2NnkFaMLhLBzdXF_8c7-Wzse7sqmPRlK9yx

The first five characters are missing in the output, as you can see.

https://lh6.googleusercontent.com/WHrNydPAeWIVioqPihf2oSHo_BS0kcL9fb6NJKmVDlP40EQ91b-eEMze0DwchHA0iNuXy9Bga26eNpdWYgqs6jB0RK0v9Nkm_d8jEpqAqheDluWFxROMJCxKjpmNJ5pJByin0Xml

Example 2:

We’ll look for the beginning of the file in this case. By setting the whence parameter to 0, we can use the seek() method to move the file reference to the beginning of the file. The 0 denotes the beginning of the file, which is the first byte. Let’s look at how to get the file cursor to the beginning of the file. Here we are writing to a text file in the proceeding example. We wanted to move the cursor to the beginning of the file after adding content to read the full file.

with open(r'D:/Users/Demos/demo.txt', "w+") as fp:

fp.write('Sample content line 1\n')

fp.write('Sample content line 2')

fp.seek(0)

print(fp.read())

https://lh4.googleusercontent.com/NvZ2FtJpk3bZei65clKPnouxaruztvJYtf46X5T1-AQves_yScD8xlHnnkTlfkjEO683fO8jp-j-1kAIVRgocV8qA0aKSGmTtQ8TxsrsAKHUahvAN8E4MQnlajU1-NMz0s7tfYpp

The text is written.

https://lh5.googleusercontent.com/bDnLlfdUtsUzuQcZiO9GRFnYOMFlwhm6Su0CIZ3Bzk6W5GBlr49IZFNBhpermV0QcOb0Sv6yuOY4LVDORLZW9PxSAmXdUHMQ199aL8UgODN4Q3mE2g7nJXiOoX5gBpsRSuQbs5oA

Below is the updated text after the successful execution of the code.

https://lh3.googleusercontent.com/R9EIw0UpS9VOQOsYj-_EcNdqTSyqTY4tubHxN-jrCnk2ulno405pnccyivrhgLJZO3F_hKhyLBZIXFD3-Ewkp-8Xp_ujMr6P0IpOmpLfVEFef2ETijAR29tJ-h2_Vu6A-yUJy5gO

Example 3:

In this example, we will seek from the end of the file. In this case, we’ll start searching at the end of the file. We set whence to 2 and offset to 0 to move the file pointer to the end of the file. The three operations listed below will be carried out in the example below. We’ll add additional content and shift the file pointer to the file’s end. The file reference will then be moved to the beginning of the file, and new information will be added there. We’ll return the file’s pointer to the beginning and carry on with the writing operation. Let’s look at how to move the file cursor to the file’s end. We’ll use an existing file for this process and open a new file in read/write mode.

with open(r'D:/Users/Demos/demo.txt', "w+") as fp:

fp.write('Sample content line 1\n')

fp.write('Sample content line 2')

fp.seek(0)

print(fp.read())

https://lh3.googleusercontent.com/SOPn2GpJFbgB9AOH96PMJVNiWniY0OtutmQX__tGChLseUd21U9KHZ7YW5O4dijf6xwsIr1tYYOJtORulAIa1gYNtvUX26VS28iitrO_YiUWANiMAud8x6-VbM59ss5UIYdvHCDa

The content is added at the end of the line.

https://lh6.googleusercontent.com/niYgroNDbQOInpjht1YJQ8NRr3WoDXGUMffeu9EFLX4LflHqhyeq2mqK0xZn1Sxkel7gzt-EYEXphgeqb3ODBZWfgR5m9p5yiqrTnuMyLpwzd_fyo8bnsSiZ_qc143u2pa2iD1AF

The demo.txt file is also updated.

https://lh3.googleusercontent.com/0Zzlfq-EoBqZraEqbOQosYFGiYKYXHObYRfc6o1QlR5nNsWATHYDq4OujUAL5vBRvI2RhAxFdzaHIcxNL9dgzFeMuzEi0FU6TV7tlCCOSVbeKPH2XjP7JN_yUo56GZSLlXPV9A7C

Example 4:

Finally, we’ll look at the current situation. We can relocate the file pointer a few positions ahead of the current position by setting whence to 1 and offset the number of the position we want to modify. If the current file pointer is at the 20th position and you want to jump to the 75th character, set offset to 50 and whence to 1. We’ll use an existing file and open a new file in read/write mode for this process. Consider the code below, which reads three bytes and converts them to bytes. The item was then advanced 10 points from its existing position. We’ve read three bytes in the last.

with open(r'D:/Users/Demos/demo.txt', "rb") as fp:

fp.seek(2)

print(fp.read(3).decode("utf-8"))

fp.seek(5, 1)

print(fp.read(3).decode("utf-8"))

https://lh4.googleusercontent.com/ViCVOkjRAbsWyiIa3K5MrFYumdDbr3Kuz6gHADNp381x2Hljnv20KtmgommHXP-HmsyUgPz9NYlo4BU4KwbEKBJehyS--N9dDEBtIdMYmlatFUIGXB7zW3pYfh7e0FGQfM594zNB

The resultant screen of the above code is as follows.

https://lh4.googleusercontent.com/xSx_r_r1bi4zkc9hthSp_WhFni8-vCUzG88btwqEtTFXfFCxbpeYmqb0HZA1er9wbs1lqYHGi9q6rtGcjb0-Qd-i_Q7QtZUMXRGUJLThShSs6JAX2BzVoXsyUatsoTkhiSFCFYjW

Conclusion:

In this article, we learned how to browse different parts or sections of a file using the filehandle. We showed you how to alter the filehandle position with the seek() method to add new content or read certain file sections.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content

Page was generated in 0.059735059738159