[英]TypeError: join() argument must be str or bytes, not 'list'
I am new to python and just learning the os.walk() and tarfile.我是 python 的新手,刚刚学习 os.walk() 和 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.
我正在尝试遍历一个包含文件和子文件夹的文件夹,并尝试将它们全部添加到 tar 文件中。 I keep getting the error "TypeError: join() argument must be str or bytes, not 'list'"
我不断收到错误消息“TypeError:join() 参数必须是 str 或 bytes,而不是‘list’”
Before I tried to add to the tar file, I have tried to just print the contents.在尝试添加到 tar 文件之前,我尝试只打印内容。 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.
我可以通过将 str 添加到 os.path.dirname 的参数来解决这个问题,但不确定这样做是否正确。
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: Output:
TypeError: join() argument must be str or bytes, not 'list''''
f_names
is a list, you need to iterate over it to get each filename separately and use in os.path.join
eg: f_names
是一个列表,您需要对其进行迭代以分别获取每个文件名并在os.path.join
使用,例如:
for root, d_names, f_names in dt:
for filename in f_names:
os.path.join(root, filename)
As heemayl pointed out f_names is a list.正如 heemayl 指出的那样, f_names 是一个列表。 Another way would be to unpack the list of filenames, so that you don't need a for loop:
另一种方法是解压文件名列表,这样就不需要 for 循环了:
for root, d_names, f_names in dt:
os.path.join(root, *f_names)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.