当我尝试在python中逐行打印文件内容时,我无法通过 f.seek(0)来回放打开的文件,以便在文件被<打开时打印内容strong> with open(“file_name”)为f: 但是,如果我使用 open(“file_name”)作为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="")
我是初学者,任何人都可以告诉我为什么?
答案 0 :(得分:2)
第一个f.seek(0)
会抛出错误,因为
with open("130.txt", "r") as f:
print (f.read())
将关闭块末尾的文件(一旦打印出文件)
您需要执行以下操作:
with open("130.txt", "r") as f:
print (f.read())
# in with block
f.seek(0)
答案 1 :(得分:0)
with
的目的是在块结束时清理资源,在这种情况下包括关闭文件句柄。
尽管如此,您应该可以在.seek
区块中with
:
with open('130.txt','r') as f:
print (f.read())
f.seek(0)
for line in f:
print (line,end='')
在你的评论中,with
在这种情况下是类似这样的语法糖:
f = open(...)
try:
# use f
finally:
f.close()
# f is still in scope, but the file handle it references has been closed