Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取文件后的EOF?_Python_File_Readlines - Fatal编程技术网

Python 读取文件后的EOF?

Python 读取文件后的EOF?,python,file,readlines,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行文本(第1行、第2行、第3行

我写了一个非常简单的代码,但有一件事我不懂。 代码看起来是这样的

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行文本(第1行、第2行、第3行、第4行)。运行此代码后,我将获得以下输出:

4
0

第一个是可以的,但是为什么第二个是0?因为之前的函数设置为EOF?如果是这样,为什么它不从一开始就读取文件?有没有重新加载文件的方法?

是的,第二种方法是
0
,因为您已经读取了整个文件,所以在
CountChars
中没有任何内容可以读取

在调用
CountChars
之前,您需要将
name.seek(0)
放在其中以返回文件的开头。看看这本书