Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Maksym Shulha
The Python "TypeError: join() argument must be str, bytes, or os.PathLike
object, not 'list'" occurs when we pass a list to the os.path.join()
method.
To solve the error, use a for
loop to pass each item of the list to the
method, or unpack the list items in the call.
Here is an example of how the error occurs.
import os my_list = ['home/alice', 'home/bob'] # ⛔️ TypeError: join() argument must be str, bytes, or os.PathLike object, not 'list' result = os.path.join('/', my_list)
We passed a list to the os.path.join()
method which caused the error.
If you need to join each string in the list to a specified root path, use a
for
loop.
import os my_list = ['home/alice', 'home/bob'] for path in my_list: result = os.path.join('/', path) print(result) # 👉️ "/home/alice", "/home/bob"
If you need to join all the paths from the list into a single path, unpack them
in the call to the os.path.join()
method.
import os my_list = ['home', 'alice', 'images'] result = os.path.join('/', *my_list) print(result) # 👉️ /home/alice/images
The os.path.join method joins one or more paths intelligently.
If any of the provided components is an absolute path, all previous components are thrown away and joining continues from the absolute path onwards.