Python中使用超出文件大小的偏移量的Seek函数
我正在尝试理解Python文件处理中的seek函数是怎么工作的。这个函数的语法是seek(offset, whence)。其中的'whence'参数就像一个参考点,可以取值0、1和2,分别表示文件的开始、当前指针的位置(可以通过'tell'函数获取)和文件的结束。假设我们打开一个二进制读取模式的文件,文件长度是22。接下来,我考虑三个程序,试图将指针移动到超出文件大小的位置。从逻辑上讲,程序应该返回一个异常或者在文件末尾停止。但是输出却不同,指针超出了边界,当尝试从那个位置读取时,输出是一个空字符串。让我来解释一下这是怎么回事。
我尝试了这三个程序,结果让我感到困惑。
程序1
whence值为0,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,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
whence值为1,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(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
whence值为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''
指针是怎么移动的呢?
1 个回答
0
当你在Python中尝试去读取文件末尾之后的内容时,文件指针会停在文件的最后面。接下来如果你再进行读取操作,就会得到一个空字符串,这表示文件已经读完了。这样的设计让你可以在文件末尾之后继续操作,而不会出现错误,这样在处理文件时就更加灵活了。