Skip to main content
 首页 » 编程设计

python之为什么我会收到此错误 '_io.TextIOWrapper' 对象没有属性 'append'

2024年11月24日37lidabo

为了解决这个错误,我已经做了很多事情,但我已经干涸了。有人知道为什么我总是收到此错误吗?

myList =[n, weather, wind, other, avgscore] 
    with open("data.txt", 'w') as f: 
        for s in myList: 
            f.append(str(s) + '\n') 
    print("Thank you, your data was logged") 

请您参考如下方法:

您需要使用 write() 而不是 append():

myList =['n', 'weather', 'wind', 'other', 'avgscore'] 
with open("list.txt", 'w') as f: 
    for s in myList: 
        f.write(str(s) + '\n') 
print("Thank you, your data was logged") 

如果您想将数据 append 到已写入的文件而不是覆盖它:

You need to open the file in append mode, by setting "a" or "ab" as the mode.

docs:

myList =['n2', 'weather2', 'wind2', 'other2', 'avgscore2'] 
with open("list.txt", 'a') as f: 
    for s in myList: 
        f.write(str(s) + '\n') 
print("Thank you, your data was logged") 

输出:

n 
weather 
wind 
other 
avgscore 
n2 
weather2 
wind2 
other2 
avgscore2