我试图找出我的文件指针是否位于 EOF 处,如以下示例代码所示:(已编辑)
f = open("test.dat")
someFunctionDoingStuffOn_f(f)
if f == EOF: # to keep something like this would be important in my case
print "EOF reached"
else:
print "Not EOF"
但我不知道Python中是否有类似的东西。
我通过添加 someFunctionDoingStuffOn_f(f) 来编辑问题,因为我可能事先不知道 f 发生了什么。这排除了一些方法。
最佳答案
根据 martijns 评论,您可以使用 tell
但我真的不知道它会产生什么影响:
import os
R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)
while R.f.tell() < n:
line = R.f.readline()
print(line)
print("Not at EOF")
print("At EOF")
其中 R.f
是 previous question 中您的类的文件对象但你不能像使用 islice 那样使用tell。
或者使用 if 来更像您问题中的逻辑:
import os
R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)
while True:
if R.f.tell() != n:
line = R.f.readline()
print(line)
print("Not at EOF")
else:
print("At EOF")
break
关于python - Python中判断文件指针是否位于EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040009/