The file is already closed (when the previous with block finishes), so you cannot do anything more to the file. To reopen the file, create another with statement and use the read attribute to read the file.
with open('test_output.txt', 'r') as f2:
data = f2.read()
print(data)
Answer from Taku on Stack OverflowTypeError: '_io.TextIOWrapper'
open() returns IO[str] instead of io.TextIOWrapper
Change class from '_io.TextIOWrapper' to 'bytes'
python - how to understand <class '_io.TextIOWrapper'>? - Stack Overflow
I'm supposed to create a dictionary from the values in a file and search for 'Polly' and remove it if it's in the file,
I kept getting errors so I'm just trying to get it to print the value just so I can see what I'm doing wrong and even at the most simple level I keep getting errors,
I'm in my first semester so this is all still new to me
employees = {}
employees = open('dictionary_values.txt', 'r')
print(employees['Polly'])
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(employees['Polly'])
TypeError: '_io.TextIOWrapper' object is not subscriptable
That expression for line in file splits (streams more accurately) the file by the new line delimiter until it reaches EOF. Think of it a stream that reads until it's a new line, and then returns the characters it just read.
File-like objects are iterators that produce a line of text on each iteration. Iterators in general just means "things you can loop over exactly once"; files differ from this pattern on insofar as they can (depending on what the represent) be seeked, which would reset the iterator to a new position in the file.
To be clear, they are not sequences; the term "sequence" has specific meaning, and includes the ability to index it, iterate it multiple times in a row or in parallel, all without manually fixing up state.
Use codecs.getreader to produce a wrapper object:
text_stream = codecs.getreader("utf-8")(bytes_stream)
Works on Python 2 and Python 3.
It turns out you just need to wrap your io.BytesIO in io.BufferedReader which exists on both Python 2 and Python 3.
import io
reader = io.BufferedReader(io.BytesIO("Lorem ipsum".encode("utf-8")))
wrapper = io.TextIOWrapper(reader)
wrapper.read() # returns Lorem ipsum
This answer originally suggested using os.pipe, but the read-side of the pipe would have to be wrapped in io.BufferedReader on Python 2 anyway to work, so this solution is simpler and avoids allocating a pipe.