Python Seek 函数,偏移量超过文件大小

问题描述 投票:0回答:1

我想了解Python文件处理中的seek函数是如何工作的。该函数的语法是seek(offset,whence)。参数 'whence' 就像一个参考点,可能的值 0,1 和 2 分别指文件的开头、指针的当前位置('tell' 函数的返回值)和文件的结尾。考虑以二进制红色模式打开文件,文件长度为 22。考虑三个程序,我尝试将指针移动到超过文件大小的位置。从逻辑上讲,程序应该返回异常或在文件末尾停止。但是,当指针超出边界时,输出会有所不同,并且当尝试从该位置读取时,输出是空字符串。解释一下它是如何工作的。

我尝试了这三个程序,但对输出感到困惑。

节目1

其中值为 0 并且偏移量大于文件大小

fp = open('sample.txt', 'rb')
print('Current position of pointer is', fp.tell())
size_of_file = len(fp.read())
print('Size of the file is', size_of_file)
fp.seek(0,0) #Bringing back the pointer to start of file
fp.seek(size_of_file + 1, 0)
print('Current position of pointer is', fp.tell())
print(fp.read())

输出是

Current position of pointer is 0
Size of the file is 22
Current position of pointer is 23
b''

节目2

其中值为 1 并且偏移量大于文件的剩余读取大小

fp = open('sample.txt', 'rb')
print('Current position of pointer is', fp.tell())
size_of_file = len(fp.read())
print('Size of the file is', size_of_file)
fp.seek(size_of_file // 2,1) #Bringing the pointer to middle of file
fp.seek((size_of_file // 2) + 1, 1)
print('Current position of pointer is', fp.tell())
print(fp.read())

输出是

Current position of pointer is 0
Size of the file is 22
Current position of pointer is 45
b''

节目3

其中 value 为 2 并且 offset 为正数

fp = open('sample.txt', 'rb')
print('Current position of pointer is', fp.tell())
size_of_file = len(fp.read())
print('Size of the file is', size_of_file)
fp.seek(0,2) #Bringing the pointer to end of file
fp.seek(1, 2)
print('Current position of pointer is', fp.tell())
print(fp.read())

输出是

Current position of pointer is 0
Size of the file is 22
Current position of pointer is 23
b''

解释指针如何移动?

python file-handling seek file-pointer
1个回答
0
投票

当您尝试在 Python 中查找文件末尾之外的位置时,文件指针位于文件末尾。从该位置开始的后续读取操作将返回一个空字符串,表明已到达文件末尾。此行为允许在不引发异常的情况下进行超出文件末尾的查找,从而提供文件操作的灵活性。

© www.soinside.com 2019 - 2024. All rights reserved.