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
相关产品推荐
相关产品推荐

