Can 'file.read() function' not be used twice?
I executed file.read() at first and it worked well but when I tried to use the function before I close the file it didn't work.
f=open("text.txt","r")
f.read()
'hello\nbye'
f.read()
''
Can 'file.read() function' not be used twice?
I executed file.read() at first and it worked well but when I tried to use the function before I close the file it didn't work.
f=open("text.txt","r")
f.read()
'hello\nbye'
f.read()
''
If the end of the file has been reached,
f.read()
will return an empty string (''
).
More information can be found here: https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
Save to an object
with open( "text.txt","r" ) as f :
file = f.readlines()
and you have the content stored in "file" object
When you read for the first time, the cursor reaches the end of file. Move cursor back to start of file with seek(0)
:
In [28]: f=open("test.txt","r")
In [29]: f.read()
Out[29]: 'hello\nbye'
In [30]: f.read()
Out[30]: ''
In [31]: f.seek(0)
Out[31]: 0
In [32]: f.read()
Out[32]: 'hello\nbye'