Python调用os.path.join拼接路径报TypeError参数为list错误
问题:os.path.join 传入os.listdir返回值触发TypeError
使用os.path模块做路径拼接时运行报错,复现代码:
filepath = os.path.join('SalesData') filepath disFile = os.listdir(filepath) disFile joinFile = os.path.join(disFile, "Sales_Data_2020")
触发的报错信息:
TypeError Traceback (most recent call last) Input In [15], in <cell line: 1>() ----> 1 joinFile=os.path.join(disFile,"Sales_Data_2020") File ~\anaconda3\lib\ntpath.py:78, in join(path, *paths) 77 def join(path, *paths): ---> 78 path = os.fspath(path) 79 if isinstance(path, bytes): 80 sep = b'\' TypeError: expected str, bytes or os.PathLike object, not list
报错根因
os.listdir()的返回值是指定目录下所有子项(文件、子文件夹)名称组成的列表,不是单个路径字符串。os.path.join()要求所有入参必须是字符串、字节串或者符合os.PathLike规范的路径对象,直接传入列表必然触发类型错误。
修复方案
根据实际需求选对应写法即可:
- 如果你是要遍历
SalesData下所有子项,给每个子项拼接Sales_Data_2020后缀路径,就遍历列表逐个拼接,记得带上上层父目录路径,不然拼出来的路径不完整:
import os filepath = os.path.join('SalesData') disFile = os.listdir(filepath) join_result = [] for item_name in disFile: # 拼接顺序:父目录 -> 当前子项名 -> 目标子路径 full_path = os.path.join(filepath, item_name, "Sales_Data_2020") join_result.append(full_path)
- 如果你只是想获取
SalesData目录下Sales_Data_2020的路径,完全不需要调用os.listdir,直接拼接就行:
target_path = os.path.join('SalesData', "Sales_Data_2020")
额外注意点
- 单参数调用
os.path.join('SalesData')没有任何拼接效果,会直接返回传入的原字符串 - 路径拼接时不要漏写上层目录,否则生成的是缺失层级的相对路径,运行时很容易出现文件找不到的问题
- Python 3.4+自带
pathlib模块,用面向对象的方式处理路径,类型提示更清晰,能减少这类传参类型错误的问题
内容的提问来源于stack exchange,提问作者Emmanuel Ocquaye
相关产品推荐
相关产品推荐

