如何解决我正在尝试将追加到现有文件为什么我需要使用.write并在使用.append时出现错误
我不明白为什么在追加文件时不能使用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'
解决方法
files
是 _io.TextIOWrapper
In [14]: isinstance(files,_io.TextIOWrapper)
Out[14]: True
此外,files
不具有append
功能:
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))
,
切换出append命令并放入write。 (保持“ a”)。这是因为有一个附加命令。但是,它用于将元素添加到列表,而write命令将编辑文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。