Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Eric Masur
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.
Here is an example of how the error occurs.
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.
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.
from pathlib import Path p = Path('/home') result = f'{p}/user/logo.png' print(result) # 👉️ "/home/user/logo.png"
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.
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.