所以我正在为一个非常基本的音乐应用程序开发代码,每个用户信息都使用以下格式保存到数据库中:
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n' )
现在我想阅读特定用户的现有信息,并允许他们更改他们的fav_genre。以下是我尝试失败的尝试:
textfile = 'user_DB.txt'
def a():
username = input('name?: ')
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
textIn.write(information[5]=new_genre)#this line
print('new genre is saved to',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
textIn.close()
a()
注释#this行的行是我认为错误正在出现的地方,因为我想用新的那个覆盖该特定用户的fav_genre的先前值。关于我可以做什么不同的任何想法使这项工作?
答案 0 :(得分:-1)
基本上将该行更改为:
textfile.write(' : '.join(information.values()) + '\n' )
如此完整的代码:
textfile = 'user_DB.txt'
updated_textfile = 'user_DB_Updated.txt'
def a():
username = input('name?: ')
updated_lines = []
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
updated_lines.append(line)
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
updated_lines[-1] = ' : '.join(information) + '\n'
print('new genre is saved to ',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
with open(updated_textfile, 'w+') as out_text:
out_text.write(''.join(updated_lines))
textfile.close()
a()