求助:Python代码报TypeError,NoneType与str无法执行+运算
问题解决:TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
错误原因
你的代码里self.current_video的值是None,Python不允许将NoneType(空值)与字符串直接拼接,执行self.current_video + ".txt"时就触发了这个类型错误。
解决方案
1. 检查变量初始化逻辑
先排查self.current_video的赋值代码,确保在执行这段代码前,它已经被正确设置为字符串类型的视频文件名(比如在类的__init__方法或前置方法中完成赋值,例如self.current_video = "sample_video")。
2. 添加防御性代码处理空值
如果无法保证self.current_video一定有值,可以添加判断逻辑避免报错:
# 方式1:主动抛出异常提示未初始化 if self.current_video is None: raise ValueError("current_video 未被正确初始化,请先设置视频名称") video_name = self.current_video + ".txt" out_filename = os.path.join(self.save_dir, video_name)
# 方式2:使用默认文件名替代空值 video_name = f"{self.current_video or 'default_video'}.txt" out_filename = os.path.join(self.save_dir, video_name)
内容的提问来源于stack exchange,提问作者01fe19bec158
相关产品推荐
相关产品推荐

