【发布时间】:2017-10-13 18:10:49
【问题描述】:
当我试图在 python 中逐行打印文件内容时,如果文件是由 with open("file_name") as f: 但是,如果我使用 open("file_name") as f: 就可以做到这一点 然后 f.seek(0)
以下是我的代码
with open("130.txt", "r") as f: #f is a FILE object
print (f.read()) #so f has method: read(), and f.read() will contain the newline each time
f.seek(0) #This will Error!
with open("130.txt", "r") as f: #Have to open it again, and I'm aware the indentation should change
for line in f:
print (line, end="")
f = open("130.txt", "r")
f.seek(0)
for line in f:
print(line, end="")
f.seek(0) #This time OK!
for line in f:
print(line, end="")
我是python初学者,谁能告诉我为什么?
【问题讨论】: