当我尝试在Python中逐行打印文件内容时,如果使用 with open("file_name") as f: 打开文件,则无法通过 f.seek(0) 倒回文件并打印内容。
但是,如果使用 open("file_name") as f: 则可以实现。
以下是我的代码:
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初学者,有谁可以告诉我为什么?
f
仍然存在并引用文件句柄的包装器,但它实际上包装的句柄已经关闭,因此当进行后续调用时将会失败。我当然希望f
的作用域限定在with
块内,但是Python对这种事情相当宽松。 - ryachza