Python 3我有一些关于 seek() 和 tell() 的问题

问题描述

我目前正在通过 Zed Shaw 的书《Learning Python 3 The Hard Way》学习 Python 3。

在做关于函数文件的练习 20 时,你会得到研究人员的任务,搜索函数是做什么的。通过在线搜索,我遇到了一些关于此功能的概念,但我无法理解:

这是我在网上找到的关于 seek() 目的的解释:

Python 文件方法 seek() 在偏移量处设置文件的当前位置。

  • 在这种情况下,“文件的当前位置”是什么意思?

这是我在网上找到的关于 tell() 目的的解释:

Python 文件方法tell() 返回文件读/写指针在文件中的当前位置。

  • 在这种情况下,“文件读/写指针”是什么意思?

解决方法

您可以将文件视为字节序列(至少如果您使用mode='rb'将文件作为二进制文件打开时是这样),类似于存储在磁盘上的bytearray .当您第一次使用 mode='rb' 打开文件时,您当前定位或“指向”文件的开头,偏移量为 0,这意味着如果您为 read 字节发出 n您将读取文件的 first n 个字节(假设文件至少有 n 个字节的数据)。读取后,您的新文件位置位于偏移 n。因此,如果您只执行连续的 read 调用,您将按顺序读取文件。

方法 tell 返回您当前的“位置”,即您在文件中的当前偏移量:

with open('myfile','rb') as f:
    data = f.read(12) # after this read I should be at offset 12
    print(f.tell()) # this should print out 12

方法 seek 允许您更改文件中的当前位置:

import os

with open('myfile','rb') as f:
    # read the last 12 bytes of the file:
    f.seek(-12,os.SEEK_END) # seek 12 bytes before the end of the file
    data = f.read(12) # after this read I should be at the end of the file