Expected str, bytes or os.PathLike object, not TextIOWrapper

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Expected str, bytes or os.PathLike object, not TextIOWrapper #

The Python "TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper" occurs when we pass a file object instead of a string when opening a file. To solve the error, pass the filename (as a string) to the open() function.

python typeerror expected str bytes or os pathlike object not textiowrapper

Here is an example of how the error occurs.

main.py
with open('example.txt', 'r', encoding='utf-8') as file1: lines = file1.readlines() print(lines) # ⛔️ TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper with open(file1, 'r', encoding='utf-8') as file2: lines = file2.readlines() print(lines)

The error was caused because we passed a file object instead of a string in the second call to the open() function.

The first argument the open() function expects is a string that represents the filename.

To solve the error, pass a string for the filename.

main.py
with open('example.txt', 'r', encoding='utf-8') as file1: lines = file1.readlines() print(lines) with open('example-2.txt', 'r', encoding='utf-8') as file2: lines = file2.readlines() print(lines)

If you need to construct the filename by concatenating strings, use a formatted string literal.

main.py
name = 'example' ext = 'txt' filename = f'{name}.{ext}' with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: print(line)
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

Conclusion #

The Python "TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper" occurs when we pass a file object instead of a string when opening a file. To solve the error, pass the filename (as a string) to the open() 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.