Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Ryan Byrne
The Python "TypeError: expected str, bytes or os.PathLike object, not tuple"
occurs when we pass a tuple instead of a string when opening a file. To solve
the error, use a for
loop if you have to open multiple files or use the
addition operator to get a filename from multiple strings.
Here is an example of how the error occurs.
# 👇️ tuple filenames = 'example-1.txt', 'example-2.txt' # ⛔️ TypeError: expected str, bytes or os.PathLike object, not tuple with open(filenames, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: print(line)
The open()
function expects a string for its first argument but we passed it a
tuple.
If you have to open multiple files, use a for
loop.
# 👇️ tuple filenames = 'example-1.txt', 'example-2.txt' for filename in filenames: with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: print(line)
We used a for
loop to iterate over the tuple and passed each filename to the
open()
function.
Notice that we are passing a string for the filename and not a tuple.
You might also get the error when trying to concatenate multiple strings to get the filename.
# 👇️ tuple filename = 'example', '.txt' # ⛔️ TypeError: expected str, bytes or os.PathLike object, not tuple with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: print(line)
The code sample creates a tuple by mistake.
One way to concatenate strings is to use the addition (+) operator.
# 👇️ this is a string filename = 'example' + '.txt' with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: print(line)
The addition (+) operator can be used to concatenate strings.
print('a' + 'b' + 'c') # 👉️ 'abc'
Alternatively, you can use a formatted string literal.
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)
f
.Make sure to wrap expressions in curly braces - {expression}
.
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorIf you aren't sure what type a variable stores, use the built-in type()
class.
my_tuple = 'example', '.txt' print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_str = 'example.txt' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.