Last updated: Apr 20, 2022
Photo from Unsplash
The Python: "TypeError: '_io.TextIOWrapper' object is not callable" occurs when we try to call a file object as if it were a function. To solve the error, make sure you don't have any clashes between function and variable names and access properties on the file object instead.
Here is an example of how the error occurs.
with open('example.txt', 'r', encoding='utf-8') as f: # ⛔️ TypeError: '_io.TextIOWrapper' object is not callable f()
We tried to call the
_io.TextIOWrapper object is if it were a function and got
If you are trying to write to a file, use the
write() method on the file
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
If you need to read from a file, use a simple
with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines) print(lines) for line in lines: print(line)
A good way to start debugging is to
print(dir(your_object)) and see what
Here is an example of what printing the attributes of a
with open('example.txt', 'r', encoding='utf-8') as f: # [... 'close', 'closed', 'detach', 'encoding', 'errors', # 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', # 'name', 'newlines', 'read', 'readable', 'readline', # 'write', 'write_through', 'writelines' ...] print(dir(f))
If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.
You probably meant to access an attribute using dot notation instead of call the
_io.TextIOWrapper as a function.