While I was trying to print file content line by line in python, I cann't rewind the opened file by f.seek(0) to print the content if the file was opened by with open("file_name") as f: but, I can do this if I use open("file_name") as f: then f.seek(0)
Following is my code
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="")
I am a python beginner, can anybody tell me why?
The first f.seek(0)
will throw an error because
with open("130.txt", "r") as f:
print (f.read())
will close the file at the end of the block (once the file has be printed out)
You'll need to do something like:
with open("130.txt", "r") as f:
print (f.read())
# in with block
f.seek(0)
The purpose of with
is to clean up the resource when the block ends, which in this case would include closing the file handle.
You should be able to .seek
within the with
block like this, though:
with open('130.txt','r') as f:
print (f.read())
f.seek(0)
for line in f:
print (line,end='')
From your comment, with
in this case is syntactic sugar for something like this:
f = open(...)
try:
# use f
finally:
f.close()
# f is still in scope, but the file handle it references has been closed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.