Python Pathlib with_suffix报错:'str'对象无此属性的问题排查
问题根源
你调用posixpath.abspath把Path对象转换成字符串后,字符串类型根本没有with_suffix方法——这个方法是pathlib.Path类独有的属性,所以会抛出AttributeError。
解决方法
别把Path对象转成字符串,全程用Path类的方法处理即可:
- 用
Path.resolve()替代posixpath.abspath获取绝对路径,返回的仍是Path对象,保留所有Path类的方法。 - 直接基于音频文件的Path对象生成对应的字幕路径,再检查是否存在。
示例代码
from pathlib import Path def find_audio_needing_transcription(root_dir): audio_extensions = ('.ogg', '.wav', '.mp3') missing_subs = [] # 递归遍历所有音频文件 for audio_path in Path(root_dir).rglob('*'): if audio_path.suffix.lower() in audio_extensions: # 生成对应的.vtt和.srt字幕路径 vtt_path = audio_path.with_suffix('.vtt') srt_path = audio_path.with_suffix('.srt') # 检查两个字幕文件是否都不存在 if not vtt_path.exists() and not srt_path.exists(): # 如需绝对路径,用audio_path.resolve(),返回还是Path对象 missing_subs.append(audio_path.resolve()) return missing_subs # 调用示例 target_dir = '/path/to/your/directory' need_transcribe = find_audio_needing_transcription(target_dir) for file in need_transcribe: print(f"需要转录的音频:{file}")
内容的提问来源于stack exchange,提问作者BashNewbie
相关产品推荐
相关产品推荐

