这段代码有什么问题?当我运行时它告诉我:
Traceback (most recent call last):
line 24, in <module>
people.append(Dict)
AttributeError: 'str' object has no attribute 'append'
我的代码:
live = 1
while live == 1:
#reading Database
dataRead = open ("db.txt","r")
if dataRead.read() != " ":
dataRead.close()
people = open ('db.txt','r').read()
do = input ('What Do You Want ? (Search , add) :\n')
#add people
if do == 'add':
#Get The New Data
n_Name = input ('enter the new name:\n')
n_age = input ('enter the new age:\n')
#new Dict
Dict = {'Name:':n_Name,'age':n_age}
people.append(Dict)
#adding people to file
dataWrite = open ("db.txt","w")
dataWrite.write(str(people))
dataWrite.close()
live = 0
最佳答案
问题是,在第 24 行,您尝试将字典附加到字符串。当您读取 db 文件时,它会将其作为字符串读取。而且代码确实很困惑,还有很多更好的方法可以做到这一点。但这不是重点,根据您的错误输出,append() 方法用于列表,变量“people”是一个字符串。
关于python - 不明白这个AttributeError的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055936/