(Python 3)我对seek()和tell()有一些问题

2024-04-29 06:00:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用Zed Shaw的书《艰苦地学习Python 3》学习Python 3

在做关于函数和文件的练习20时,您会被指派给研究员查找函数的任务。通过在线搜索,我遇到了一些关于此功能的概念,我很难理解这些概念:

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

Python file method seek() sets the file's current position at the offset.

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

以下是我在网上找到的关于tell()用途的解释:

Python file method tell() returns the current position of the file read/write pointer within the file.

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

Tags: 文件the函数概念情况positionseekcurrent
1条回答
网友
1楼 · 发布于 2024-04-29 06:00:58

您可以将文件视为一个字节序列(如果使用mode='rb'将文件作为二进制文件打开,至少是这样),类似于存储在磁盘上的bytearray。当您第一次使用mode='rb'打开文件时,您当前位于或“指向”文件的开头,偏移量为0,这意味着如果您为n字节发出read,您将读取文件的第一个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

相关问题 更多 >