首页 > 解决方案 > 用得到的结果覆盖文本文件

问题描述

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()

标签: python

解决方案


您的变量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,而无需明确写回任何内容。


推荐阅读