Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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
为什么“with open(file.txt)”语句中的第二行在python中返回空字符串?_Python_Python 3.x_With Statement - Fatal编程技术网

为什么“with open(file.txt)”语句中的第二行在python中返回空字符串?

为什么“with open(file.txt)”语句中的第二行在python中返回空字符串?,python,python-3.x,with-statement,Python,Python 3.x,With Statement,我正在学习如何用python打开文本文件,并尝试了以下代码: from pathlib import Path file_path = Path(r'path\to\file.txt') with open(file_path) as file_object: for line in file_object: print(line) contents = file_object.read() print(contents) 假设file.txt包含三个单

我正在学习如何用python打开文本文件,并尝试了以下代码:

from pathlib import Path

file_path = Path(r'path\to\file.txt')

with open(file_path) as file_object:
    for line in file_object:
        print(line)
    contents = file_object.read()


print(contents)
假设file.txt包含三个单词,每个单词在单独的一行上。for循环正常执行并打印三行,但是会为变量内容分配一个空字符串,因此最后的print语句不会显示任何内容

我猜当执行with之后的第一条语句时,文件是关闭的


谢谢你的帮助

在for循环之后,当前位置位于文件末尾。.read调用读取文件的其余部分,因为它已经在末尾了,所以它什么都不是。该文件仍处于打开状态,因此它不是一个错误,只是没有更多的内容可供读取,因为它已全部读取


如果您想再次阅读文件,您需要打电话将当前位置返回到文件开头。

谢谢您的回答。我找不到类似的问题,因为我没有意识到代码确实在文件上迭代。关键词很棘手。。。