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

Python覆写文本文件报AttributeError:'str'对象无write属性解决方法

错误说明

执行文件覆写逻辑时触发报错:AttributeError: 'str' object has no attribute 'write'

原问题代码

import os
path = r'C:\Users\CL\Desktop\folder\1'
files = os.listdir(path)

for f in files: # 遍历路径下所有文件
    full_path = open(path + "\\" + f,"r") # 拼接路径+文件名打开文件
    full_path_read = full_path.read() # 读取文件内容
    # 每8个字符插入换行符
    res = '\n'.join(full_path_read[i:i + 8] for i in range(0, len(full_path_read), 8))
    f.write(res) # 用结果覆写原文件
    f.close()
错误根因
  • os.listdir()返回的是目标路径下的文件名字符串,遍历得到的f是字符串类型,不具备文件对象的写入、关闭方法
  • 读文件时生成的文件对象被赋值给了full_path,写入逻辑错把文件名f当成了文件对象调用方法
可运行修复代码
import os
path = r'C:\Users\CL\Desktop\folder\1'
files = os.listdir(path)

for f in files:
    full_path = open(path + "\\" + f,"r")
    full_path_read = full_path.read()
    res = '\n'.join(full_path_read[i:i + 8] for i in range(0, len(full_path_read), 8))
    full_path.close()
    # 重新以写入模式打开文件,得到文件对象赋值给f
    f = open(path + "\\" + f,"w")
    f.write(res)
    f.close()
更安全的优化写法(推荐)

用with上下文管理器自动处理文件关闭,避免遗漏释放资源,同时用os.path.join拼接路径适配不同操作系统:

import os
path = r'C:\Users\CL\Desktop\folder\1'
files = os.listdir(path)

for filename in files:
    file_path = os.path.join(path, filename)
    # 读取文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    # 格式化内容
    res = '\n'.join(content[i:i+8] for i in range(0, len(content), 8))
    # 写入新内容
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(res)

内容的提问来源于stack exchange,提问作者panzers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:00:03