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'
Implement buffered io streams (io.TextIOWrapper and friends)
What Is the Role of io.TextIOWrapper in Python Input Handling?
Change class from '_io.TextIOWrapper' to 'bytes'
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.
I am doing one of the practice projects from chapter 9 of ATBS where you have to write a program that opens all text files in a folder and searches for any line that matches a regular expression.
here is my code
and here is the output
I am nowhere near finished with it yet and I'm sure there are other problems with what I've got so far, but I'm mainly concerned with the io.TextIOWrapper issue in the for loop.
It may be (probably is) caused by the way I'm trying to split the list and read each file, if that's the case, what is a better way to tackle opening each file individually? But I also want to know why the io.TextIOWrapper message is coming up for future reference.
Any help greatly appreciated! Sorry for making you look at hideous code!