os.path.join返回bytes引发类型警告?原因及解决方法
问题分析与解决:os.path.join返回bytes类型及imghdr类型警告
为什么os.path.join返回bytes类型?
你传入os.path.join的两个参数都是bytes类型:
directory是os.fsencode('./cache_folder')的返回值,os.fsencode的作用就是把字符串路径编码为bytes类型;str.encode(file_name)把字符串file_name转成了bytes类型。
Python中os.path.join的行为是:如果所有传入的路径组件都是bytes,就返回bytes类型;如果都是字符串,就返回字符串类型;混合传入字符串和bytes会直接报错。你之前认为它返回PathLike[str],是基于传入字符串路径的场景,这里参数全是bytes,所以返回bytes。
解决方案
方案一:全程使用字符串路径(推荐)
直接用字符串处理路径,避免不必要的bytes转换,更符合Python路径操作的常规写法,也能直接满足imghdr.what的参数要求:
file_name = parse.unquote(os.path.basename(parse.urlparse(src).path)) directory = './cache_folder' # 直接使用字符串路径 file_path = os.path.join(directory, file_name) # 拼接后得到字符串类型路径 img_type = imghdr.what(file_path) # 注意:imghdr.what可能返回None(无法识别文件类型),需先判断非None再调用upper() if img_type is not None and img_type.upper() not in ['J']: # 执行你的业务逻辑
方案二:将bytes路径转换为字符串
如果因为某些原因必须使用bytes路径处理,需要用os.fsdecode(和os.fsencode配对的解码方法,适配系统编码)把bytes路径转回字符串,再传给imghdr.what:
file_name = parse.unquote(os.path.basename(parse.urlparse(src).path)) directory = os.fsencode('./cache_folder') file_path = os.path.join(directory, str.encode(file_name)) # 把bytes路径解码为字符串 str_file_path = os.fsdecode(file_path) img_type = imghdr.what(str_file_path) if img_type is not None and img_type.upper() not in ['J']: # 执行你的业务逻辑
内容的提问来源于stack exchange,提问作者Albert
相关产品推荐
相关产品推荐

