-1

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()
''
Saurabh P Bhandari
  • 5,214
  • 1
  • 13
  • 40
yerim
  • 1
  • 1
  • 3
    The first time you read it the file pointer has moved to the end of the file. The second time, there's nothing left to read. – jonrsharpe Jun 20 '19 at 13:40
  • Reading a file is like using a bookmark, each time you read something you start from the bookmark and move the bookmark accordingly. If you want to read something again you'll have to : move the bookmark back or reopen the file in someway. – Jean-Baptiste Yunès Jun 20 '19 at 14:34

3 Answers3

2

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

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Vaibhav Sharma
  • 891
  • 4
  • 14
1

Save to an object

with open( "text.txt","r" ) as f :
    file = f.readlines()

and you have the content stored in "file" object

cccnrc
  • 1,144
  • 10
  • 24
1

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'
amanb
  • 4,641
  • 2
  • 17
  • 36