python - Python中判断文件指针是否位于EOF

标签 python python-2.7

我试图找出我的文件指针是否位于 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.fprevious 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/

相关文章:

python - 嵌套列表上的 min/max 函数如何工作?

python - 使用 numpy 忽略多个变量(包括函数)

python - Pandas/Python - 根据值匹配更新数据帧

python - 屏幕填充不起作用

multithreading - 当没有 .join() 时,Python 中的线程会发生什么?

Python format() 传递一个对象

python - 在 Sklearn 中使用 GridSearchCV 进行 OneVsRestClassification

python - 在 BaseProxy 上调用方法时如何有效地使用 asyncio?

python - Numpy 未安装,也 "Can' 在以下目录中找不到可用的 init.tcl :"

windows - PyQt QFileDialog getOpenFileName 无法从命令行(Windows)工作