Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting unsupportedoperation: read

I am new to python and I am having an issue with the following syntax

  test_file = open("test.txt", "wb")
  test_file.write(bytes("Write me to the file\n", 'UTF-8'))
  test_file.close()
  text_file = open("test.txt","r+")
  text_in_file = test_file.read() # this is where the error emerges
  # more code goes here

On this syntax, I am getting

io.UnsupportedOperation: read

I got it from an online tutorial and I am using python 3. do you know what could lead to such kind of error message?


1 Answers

It's a typo. You have opened text_file, but the line

text_in_file = test_file.read()

wants to read from the closed test_file. Change the line to:

text_in_file = text_file.read()
like image 127
Heiko Oberdiek Avatar answered Sep 16 '25 10:09

Heiko Oberdiek