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

Python逐行读取文件调用strip()报AttributeError如何解决

报错原因

strip()是Python字符串类型的内置方法,仅支持对字符串对象调用。
你的代码用for line in compfile遍历文件时:

  • compfile是open()返回的文件句柄对象,类型为_io.TextIOWrapper,本身不存在strip()方法
  • 每次循环迭代取出的line才是存储当前行内容的字符串对象,支持调用strip()去除首尾换行、空白字符
    你误将文件对象作为strip()的调用主体,才触发了属性不存在的报错。
修复方案

核心修改点:把循环内调用strip()的对象从compfile改为行变量line即可。
额外优化建议:

  • 打开文件时显式指定encoding='utf-8',避免不同操作系统默认编码差异导致的乱码问题
  • 优先使用with上下文管理器操作文件,会在逻辑块结束后自动关闭文件,无需手动调用close()

最小改动版(保留原有代码结构,仅修正错误)

compfile = open(input('path:'), 'r', encoding='utf-8')
count = 0
for line in compfile:
    count += 1
    print("Line{}: {}".format(count, line.strip()))
compfile.close()

规范写法(自动管理文件生命周期)

count = 0
with open(input('path:'), 'r', encoding='utf-8') as compfile:
    for line in compfile:
        count += 1
        print(f"Line{count}: {line.strip()}")

内容的提问来源于stack exchange,提问作者UserThatProgram'sHorribly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 08:36:17