python - 用得到的结果覆盖文本文件
问题描述
Gd天同胞专家,
我想用我得到的结果覆盖我的文件,但遇到错误:AttributeError: 'str' object has no attribute 'write'
当前代码
path = r'C:\Users\CL\Desktop\folder\1'
files = os.listdir(path)
for f in files: #read all files in path folder
full_path = open(path + "\\" + f,"r") #join path + file name
full_path_read = full_path.read() #read file
res = '\n'.join(full_path_read[i:i + 8] for i in range(0, len(full_path_read), 8)) #break sentence every 8th character
f.write(res) #overwrite file with result
f.close()
编辑的解决方案(它有效:))
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 = open(path + "\\" + f,"w")
f.write(res)
f.close()
解决方案
您的变量full_path
实际上并不包含完整路径;相反,它包含一个打开以供读取的文件句柄。
一个简单的解决方法是更改代码以使其full_path
实际包含完整路径,然后再次打开文件进行写入,然后写入。
path = r'C:\Users\CL\Desktop\folder\1'
for f in os.listdir(path):
full_path = os.path.join(path, f)
with open(full_path, "r") as readhandle:
full_path_read = readhandle.read()
res = '\n'.join(full_path_read[i:i + 8] for i in range(0, len(full_path_read), 8))
with open(full_path, "w") as writehandle:
writehandle.write(res)
还要注意如何with open
不需要显式地close()
显示文件。
但是,如果文件很大,也许更好的解决方案是一次读取一行,并只跟踪前一行的第一段中保留多少字符。然后,您可以在其模式下使用该fileinput
模块inplace=True
,而无需明确写回任何内容。
推荐阅读
- java - 如何从 firebase 实时数据库中获取子值?
- postgresql - 我需要创建一个带有两个外键的表,这两个外键都是另一个表的主键
- hibernate - 在Hibernate中删除@OneToMany中的父记录时将子记录外键设置为null
- python - 将 SQL 查询读入 pandas 数据帧并替换查询中的字符串
- javascript - 更新状态导致测试不停止
- typescript - TypeScript 模板文字类型 - 如何推断数字类型?
- c++ - C++ V 形铸造:矢量
向量 - regex - 在评论中为 git check 编写正则表达式
- wcf - WCF 基于证书的身份验证接受同一根证书颁发机构签名的所有证书
- asammdf - 使用 ASAMMDF 编写比例/嵌套转换