TypeError: join() argument must be str or bytes not 'list'

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Maksym Shulha

TypeError: join() argument must be str or bytes not 'list' #

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.

main.py
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.

main.py
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.

main.py
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.

The method concatenates the provided paths with exactly one directory separator following each non-empty part except the last.

If any of the provided components is an absolute path, all previous components are thrown away and joining continues from the absolute path onwards.

Use the search field on my Home Page to filter through my more than 1,000 articles.