You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:41:59