Getting Started with Python documents: seek () and tell () function

 

 

  When the Python open () function to open the file and read the contents of a file, always from the first character of the file (byte) began to read from.

Well, there is no way you can custom specify the starting position read it?

To achieve movement of the file pointer, a file object provides tell () function, and seek () function. tell () function for determining the position of the file pointer is currently located, and seek () function is used to move the file pointer of the file to the specified location.

The meaning of the various parameters is as follows:

  • file: file objects;
  • The whence: as an optional parameter, specifies the location of the file pointer to be placed, the parameter value of the parameter has three options: 0 = Header (default), 1 represents the current position, represents the file.
  • offset: indicates the offset from whence file pointer position, positive number indicates an offset rearwardly, forwardly offset a negative number. For example, when whence == 0 &&offset == 3(i.e., seek (3,0)), it indicates that the file pointer to a file at a location from the beginning of three characters; if whence == 1 &&offset == 5(i.e. seek (5,1)), indicates that the file pointer is moved backward, to move from the current location 5 character.
file.tell()

file.seek(offset,[whence])

f = open('a.txt', 'rb')

print(f.tell())               # 判断文件指针的位置

print(f.read(1))              # 读取一个字节,文件指针自动后移1个数据
print(f.tell())

f.seek(5)                    # 将文件指针从文件开头,向后移动到 5 个字符的位置
print(f.tell())
print(f.read(1))


f.seek(5, 1)                 # 将文件指针从当前位置,向后移动到 5 个字符的位置
print(f.tell())
print(f.read(1))

f.seek(-1, 2)               # 将文件指针从文件结尾,向前移动到距离 10 个字符的位置
print(f.tell())
print(f.read(1))

 

 

 

 

 

 

Published 96 original articles · won praise 76 · views 40000 +

Guess you like

Origin blog.csdn.net/u010244992/article/details/104934295
Recommended