在 python 中与 open() 一起使用后,seek(0) 如何无法倒带打开的文件
How opened file cannot be rewind by seek(0) after using with open() in python
当我试图在 python 中逐行打印文件内容时,我无法通过 f.seek(0) 倒带打开的文件如果文件是由 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初学者,谁能告诉我为什么?
第一个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)
with
的目的是在块结束时清理资源,在本例中包括关闭文件句柄。
您应该可以在 with
块中 .seek
,但是:
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
当我试图在 python 中逐行打印文件内容时,我无法通过 f.seek(0) 倒带打开的文件如果文件是由 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初学者,谁能告诉我为什么?
第一个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)
with
的目的是在块结束时清理资源,在本例中包括关闭文件句柄。
您应该可以在 with
块中 .seek
,但是:
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