如何打印特定用户的fav_genre字段

2024-10-17 08:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,下面的代码将变量username pass etc保存到一个文本文件中,用冒号分隔每个字段。假设我想打印出某个特定用户最喜欢的类型,那怎么可能呢,因为到目前为止我的尝试都失败了。顺便说一句,这都是用python编写的。我编辑了添加我的尝试,但没有效果。有什么想法吗

usrFile_write = open(textfile, 'a')
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n')
print('New Account Created!')
print()
usrFile_write.close()
Menu()

我的尝试:

textfile = 'user_DB.txt'
username = 'dj'
def getUsersFavouriteGenre():
    with open(textfile, 'r') as textIn:
        for line in textIn:
            information = line.split(' : ')
            if information[0] == username:
                return information[5]
    return 'Failed to find user.'

getUsersFavouriteGenre()

Tags: 代码returninformationlineusernamepassopenwrite
1条回答
网友
1楼 · 发布于 2024-10-17 08:20:05

你的代码看起来不错。我假设问题是您的程序没有输出任何内容,在这种情况下,我看到的唯一问题是将最后一行getUsersFavouriteGenre()更改为print(getUsersFavouriteGenre())

如果您收到特定错误或不需要的输出,那么您可以让我们知道,我们可以更具体地帮助您

相关问题 更多 >