打印 file.read() 不显示文件内容

Printing file.read() doesn't display file content

我无法理解为什么 file.read() 在将其保存在变量中时表现不同。这是插图:

with open("file.txt","r") as file:
    content=file.read()
    print(content)
    print("------")
    print(file.read())

输出为:

a
b

------

所以,代码的最后一行没有打印出任何东西。

有人愿意解释为什么吗?

文件对象是;从他们那里阅读会提高文件位置。再次阅读不会重置该文件位置,并且由于没有向文件添加新数据,您会返回一个空字符串。

如果需要将文件位置重置为开头,请使用file.seek() method

file.seek(0)
print(file.read())