-1

I ve been learning about files in python 3.9.6 when this happen:

  • I open a file using the open command
  • Write to a file
  • printed the text with file.read()
  • the file.read() type is str
  • print (file.read()) will return nothing .

I am using python 3.9.6 , pycharm community and python IDLE gave the same result, and the problem is , i assumed that if we passed th file.read() which is a string , the print command will be able to actually print it .

>>>file1 = open('t.txt', 'a')
>>>file1.write('hahah')
>>>file1.close()
>>>file1 = open('t.txt', 'r')
>>>file1.read()
'hahah'
>>>print(file1.read())

>>>type(file1.read())
<class 'str'>
desertnaut
  • 57,590
  • 26
  • 140
  • 166
George
  • 1
  • After the first `read()`, you have read the entire contents of the file. Subsequent `read`s have nothing left to return. Assign the result of `read()` to a variable if you want to refer to it multiple times. – khelwood Jul 31 '21 at 09:22

1 Answers1

0

As you can read here: https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

the problem is that you are read the all the file in the first file.read(), which means that you get to the end of the file, so every time (until you will close the file) that you will run file.read() you will get empty string ('').

desertnaut
  • 57,590
  • 26
  • 140
  • 166
AdielM
  • 31
  • 3