Unsupported operand type(s) for +: 'PosixPath' and 'str'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Unsupported operand type(s) for +: 'PosixPath' and 'str' #

The Python "Unsupported operand type(s) for +: 'PosixPath' and 'str'" occurs when we try to use the addition (+) operator with a PosixPath object and a string. To solve the error, use the str() class to convert the path object to a string.

typeerror unsupported operand type for plus posixpath and str

Here is an example of how the error occurs.

main.py
from pathlib import Path p = Path('/home') # ⛔️ TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str' result = p + '/user/logo.png'

We are trying to use the addition (+) operator with a PosixPath object and a string.

To solve the error, we have to convert the path object to a string.

main.py
from pathlib import Path p = Path('/home') result = str(p) + '/user/logo.png' print(result) # 👉️ "/home/user/logo.png"

We used the str() class to convert the PosixPath to the string and concatenated the strings.

Alternatively, you can use a formatted string literal.

main.py
from pathlib import Path p = Path('/home') result = f'{p}/user/logo.png' print(result) # 👉️ "/home/user/logo.png"
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}.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
from pathlib import Path p = Path('/home') print(type(p)) # 👉️ <class 'pathlib.PosixPath'> print(isinstance(p, Path)) # 👉️ True my_str = '/user/logo.png' 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.

Conclusion #

The Python "Unsupported operand type(s) for +: 'PosixPath' and 'str'" occurs when we try to use the addition (+) operator with a PosixPath object and a string. To solve the error, use the str() class to convert the path object to a string.

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.