文件的指针


一、什么是指针

1、使用read方法不能重复读取文件的数据

with open('test.txt', 'r', encoding='utf-8') as file:
    print(file.read())
    print(file.read())

2、读取数据时会移动文件的指针

二、如何使用指针

1、使用tell方法查看文件中指针距离开头的位置

with open('test.txt', 'r', encoding='utf-8') as file:
    print(file.read(2))
    print(file.tell())
    print(file.read())

2、使用seek方法移动指针到指定位置

with open('test.txt', 'r', encoding='utf-8') as file:
    print(file.tell())
    file.seek(2, 0)
    print(file.tell())

3、seek方法有两个参数(偏移量参数和位置参数)

(1)、位置参数只可选择0(文件开头)、1(当前位置)、2(文件尾部)

(2)、当位置参数为1(当前位置)或2(文件尾部)时偏移量参数必需为0

results matching ""

    No results matching ""