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

Question:

I am new to python and just learning the os.walk() and tarfile. I am trying to traverse a folder which has files and subfolders with files, and trying to add all of them to tar file. I keep getting the error “TypeError: join() argument must be str or bytes, not ‘list'”

Before I tried to add to the tar file, I have tried to just print the contents. Gives the same error. I can get through that by adding str to the parameters of the os.path.dirname but not sure if that is the right thing to do.

import tarfile
import os

tnt = tarfile.open("sample.tar.gz", 'w:gz')

dt = os.walk('C:\users\cap\desktop\test1')
for root, d_names, f_names in dt:
   print(os.path.join((root), (f_names))) #error
   tnt.add(os.path.join(root, f_names) #error
tnt.close()

print(os.path.join((root), (f_names)))
genericpath._check_arg_types('join', path, *paths)

Output:

TypeError: join() argument must be str or bytes, not 'list''''
Asked By: coder_3476

||

Answers:

f_names is a list, you need to iterate over it to get each filename separately and use in os.path.join e.g.:

for root, d_names, f_names in dt:
    for filename in f_names:
        os.path.join(root, filename)
Answered By: heemayl

As heemayl pointed out f_names is a list. Another way would be to unpack the list of filenames, so that you don’t need a for loop:

for root, d_names, f_names in dt:
    os.path.join(root, *f_names)
Answered By: awied1404
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.