27 Python regular course - Advanced file: Move the pointer

In this article authors are all original, For reprint, please indicate the source: https://www.cnblogs.com/xuexianqi/p/12503359.htmll

A: Pointer

Pointer movement unit is in bytes / bytes

Only one special case: read (n) at t pattern, n represents the number of characters

with open('aaa.txt',mode='rt',encoding='utf-8') as f:
    res=f.read(4)
    print(res)

II: Mode

f.seek (n, mode): n refers to the number of bytes moved

1. Mode 0: The reference position is the beginning of the document

f.seek(9,0)
f.seek(3,0) # 3

2. Mode 1: reference location is the current location pointer

f.seek(9,1)
f.seek(3,1) # 12

3. Mode 2: The reference position is the end of the file, you should move backwards

f.seek(-9,2) # 3
f.seek(-3,2) # 9

Emphasized: Only mode may be used at 0 t, 1,2 must be used in the mode b

III: Demonstration

with open('aaa.txt',mode='rb') as f:
    f.seek(9,0)
    f.seek(3,0) # 3
    # print(f.tell())
    f.seek(4,0)
    res=f.read()
    print(res.decode('utf-8'))
with open('aaa.txt',mode='rb') as f:
    f.seek(9,1)
    f.seek(3,1) # 12
    print(f.tell())
with open('aaa.txt',mode='rb') as f:
    f.seek(-9,2)
    # print(f.tell())
    f.seek(-3,2)
    # print(f.tell())
    print(f.read().decode('utf-8'))

Guess you like

Origin www.cnblogs.com/xuexianqi/p/12503359.html