Python遍历C盘查找TXT文件时出现AttributeError: 'str'无append属性错误
问题修复方案
错误根源
你在循环里误将原本是列表的file_paths重新赋值成了字符串:
file_paths, file_ext = os.path.splitext(root+'\\'+file)
os.path.splitext返回的是**(无后缀文件名, 后缀)**的元组,这行代码把第一个字符串值覆盖了初始定义的file_paths列表,导致后续调用file_paths.append()时,因为对象已经变成字符串,自然报错AttributeError: 'str' object has no attribute 'append'。
修复后的代码
import os find_ext = ('.txt',) file_paths = [] for root, dirs, files in os.walk('C:\\'): for file in files: # 改用新变量存储无后缀文件名,避免覆盖列表;用os.path.join替代手动拼接路径,兼容性更好 _, file_ext = os.path.splitext(os.path.join(root, file)) if file_ext in find_ext: file_paths.append(os.path.join(root, file))
额外优化说明
- 用
os.path.join(root, file)替代root+'\\'+file,自动适配不同系统的路径分隔符,代码更通用 - 无后缀文件名如果用不到,可以用下划线
_作为占位符,更符合Python编码习惯
内容的提问来源于stack exchange,提问作者TheWizard
相关产品推荐
相关产品推荐

