TypeError: '_io.TextIOWrapper' object is not callable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: '_io.TextIOWrapper' object is not callable #

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.

typeerror io textiowrapper object is not callable

Here is an example of how the error occurs.

main.py
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 the error.

If you are trying to write to a file, use the write() method on the file object.

main.py
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 for loop.

main.py
with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines) print(lines[0]) for line in lines: print(line)
Make sure you don't have any clashes with variables and functions sharing the same name.

A good way to start debugging is to print(dir(your_object)) and see what attributes a _io.TextIOWrapper has.

Here is an example of what printing the attributes of a _io.TextIOWrapper looks like.

main.py
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.