Python 我正在尝试将附加到现有文件。为什么在使用.append时需要使用.write并获取错误

Python 我正在尝试将附加到现有文件。为什么在使用.append时需要使用.write并获取错误,python,python-3.x,Python,Python 3.x,我不明白为什么在附加到文件时不能使用append 这是我的代码: # opening capital.txt and append to it files = open('capitals.txt', 'a') userInput = input('Type the name of the city you want to add on capitals: ') # If I change this to files.write it works files.append(f'{userIn

我不明白为什么在附加到文件时不能使用append

这是我的代码:

# opening capital.txt and append to it
files = open('capitals.txt', 'a') 
userInput = input('Type the name of the city you want to add on capitals: ')

# If I change this to files.write it works
files.append(f'{userInput}') 
files.close()
我只需要解释一下为什么
.write
有效,而不是
.append

当我使用
.append
时,我得到以下错误:

> AttributeError: '_io.TextIOWrapper' object has no attribute 'append'

关闭append命令并输入write。(保留“a”)。这是因为有一个append命令;但是,它用于将元素添加到列表中,而write命令将编辑文件。

文件
\u io.TextIOWrapper

In [14]: isinstance(files, _io.TextIOWrapper)                                                                                                                  
Out[14]: True
另外,
文件
没有
追加
功能:

In [15]: hasattr(_io.TextIOWrapper, "write")                                                                                                                  
Out[15]: True

In [16]: hasattr(_io.TextIOWrapper, "append")                                                                                                                 
Out[16]: False
我认为这是您的代码的一个更具python风格的版本:

with open("capitals.txt", "a") as log:
    msg = input("Type the name of the city: ")
    log.write("{}\n".format(msg))

为什么您认为
“\u io.TextIOWrapper”对象没有属性“append”
?是什么让你认为它会有一个
append
方法呢?这能回答你的问题吗。“我只需要解释为什么.write可以工作,但不能.append”因为,正如错误消息明确指出的那样,“\u io.TextIOWrapper”对象没有属性“append”。你到底在问什么?你是在问为什么会这样?因为答案是:因为API的设计者是这样写的。它不起作用,因为append不是一个类方法,它不存在。。。写是这样的……当您使用“append”write方法打开一个文件时,这意味着当您编写时,您是在追加,您应该解释您的答案,而不仅仅是告诉OP该做什么。