-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
  • 6,014
  • 1
  • 19
  • 50
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
  • 115,751
  • 26
  • 228
  • 437
static const
  • 953
  • 4
  • 16
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,195
  • 11
  • 27
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
  • 5,276
  • 3
  • 19
  • 38