为什么会出现此错误? '_io.TextIOWrapper'对象没有属性'append'

时间:2019-03-14 11:51:52

标签: python append

我已经为避免该错误而烦恼很多,但是我快要干了。有人知道我为什么不断收到此错误吗?

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

1 个答案:

答案 0 :(得分:1)

您需要使用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")

如果您想将数据附加到已写入的文件中而不要覆盖它:

  

您需要以附加模式打开文件,方法是将“ a”或“ ab”设置为   模式。

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