读取文件后的EOF?

时间:2012-03-17 17:42:29

标签: python file readlines

我写了一个非常简单的代码,但我无法理解一件事。 代码看起来像那样

name = open("test.txt")

def CountLines(name):
    return len(name.readlines())

def CountChars(name):
    return len(name.read())


print(CountLines(name))
print(CountChars(name))

现在让我们说“test.txt”包含4行文本(line1,line2,line3,line4)。运行此代码后,我将获得输出:

4
0

第一个是好的,但为什么第二个是0?因为早期的功能设置为EOF?如果是这样,为什么它从一开始就不读取文件?有没有办法重新加载文件?

1 个答案:

答案 0 :(得分:2)

是的,第二个是0,因为您已经阅读了整个文件,因此在CountChars中无需阅读任何内容。

在调用name.seek(0)之前,您需要在其中放置CountChars以返回文件的开头。查看file object documentation