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

标签 python

因此,下面的代码将变量 username pass 等保存到文本文件中,并用冒号分隔每个字段。假设我想打印出特定用户最喜欢的类型,这怎么可能,因为到目前为止我的尝试都失败了。顺便说一句,这一切都在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()

最佳答案

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

如果您遇到特定错误或不需要的输出,您可以告知我们,我们可以为您提供更具体的帮助。

关于python - 如何打印特定用户的 fav_genre 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47296031/

相关文章:

python - 如何从多个等长数组中删除相同的随机项?

python - Pandas groupby(...).mean() 丢失 key

python - 获取 3D 空间中某个点的 26 个最近邻点 - 矢量化

python - 在 python 中将 JSON 字典转换为 JSON 数组

python - 使用 Python 的 C++ 扩展了解内存泄漏

python - Seaborn rc 中的 font_scale 与 font.size

python - 杀死 less(1) 子进程后输入失败

python - Python 中的蒙特卡罗方法

当进程终止时Python锁就会消失

python - 将 OrderedDict 转换为 python 中的集合