Python file Seek () method

Source: Internet
Author: User

Overview

The Python file Seek () method is used to move the file read pointer to the specified location.

Grammar

The Seek () method syntax is as follows:

Fileobject.seek (Offset[,whence])
Parameters
    • Offset--offsets, which represent the number of bytes that need to move the offset, note that the byte length is different for each character encoded in bytes.

such as "Lu Fei Learning City" with GBK is 2 bytes A word, with Utf-8 is 3 bytes, so when opened with GBK, Seek (4) the cursor to the "Fly" and "learn" the middle of two words.
But if it is Utf8,seek (4) will lead to, get the word fly part of the byte, printed words will be error, because processing the remainder of the text found with UTF8 can't handle, because the code is not up. A byte is missing.

    • whence: optional, default value is 0. Indicates from which position to start the offset; 0 represents starting at the beginning of the file, 1 representing starting at the current position, and 2 representing the end of the file.

return value

The function does not return a value.

Instance

The following example demonstrates the use of the Seek () method:

The contents of the file Runoob.txt are as follows:

1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com

To iterate through the contents of a file:

#!/usr/bin/python3# Open File fo = open ("Runoob.txt", "r+", encoding= "Utf-8") print ("File name:", fo.name) line = Fo.readline () Print ("Read data:%s"% (line)) # Reset file read pointer to start Fo.seek (0,0) line = Fo.readline () print ("Read data:%s"% (line)) # Close file Fo.close ()

The result of the above example output is:

The file name is: Runoob.txt reads the data:  1:www.runoob.com reads: 1:www.runoob.com

Python file Seek () method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.