当我尝试在 python 中逐行打印文件内容时,如果文件是通过with open("file_name") as f打开的,则无法通过f.seek(0)倒回打开的文件来打印内容: 但是,如果我使用open("file_name") as f: then 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="")
Run Code Online (Sandbox Code Playgroud)
我是 python 初学者,有人能告诉我为什么吗?
第一个f.seek(0)
会抛出错误,因为
with open("130.txt", "r") as f:
print (f.read())
Run Code Online (Sandbox Code Playgroud)
将在块末尾关闭文件(一旦文件被打印出来)
你需要做类似的事情:
with open("130.txt", "r") as f:
print (f.read())
# in with block
f.seek(0)
Run Code Online (Sandbox Code Playgroud)