python - 将游戏名称添加到文件中?

标签 python python-3.x while-loop

您好,我正在按照这些说明做学校作业

Write a while loop that prompts users for their favorite game. When they enter the name of the game, print a message to the screen and add a line recording their log in a file called games.txt. Make sure each entry appears on a new line in the file.

我无法多次询问循环,而不是一遍又一遍地添加游戏。另外,我不希望 games.txt 文件丢失之前添加的游戏。

<小时/>

这是我当前的代码:

filename = 'games.txt'
print("When you want to finish adding games just type 'done'")
game = input('Whats your favorite game? ')

with open(filename, 'w') as file_object:
    while game != 'done':
        print(game)
        file_object.write(game + str("\n)

如您所见,如果我运行它并将“命运 2”作为游戏,它会不断将命运 2 添加到名为 games.txt 的文件中,直到我停止程序。

最佳答案

您当前有一个无限循环,无限期地写入文件中输入的最后一个游戏名称。

您必须将输入提示放在 while 循环中。
我认为最好先将所有数据收集到一个列表中,然后再写入文件。

filename = 'games.txt'
print("When you want to finish adding games just type 'done'")

games = []
game = ''
while True:
    game = input('Whats your favorite game? ')
    if game == 'done':
        break
    games.append(game)

with open(filename, 'w') as file_object:
    for game in games:
        file_object.write(game + str("\n"))

关于python - 将游戏名称添加到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46820963/

相关文章:

javascript - 估计服务器上的客户端字体渲染大小?

python - Celery - 如何使用多个队列?

python - 用户定义的支持加法的int类

java - 尝试使用 while 循环继续循环,直到用户输入 n (Java)

java - 如何在java中仅使用while循环打印带有星号的正方形?

python - 动态地从 PIL 提供图像

python - 如何使相等数字参数出现的键值

python matplotlib plotfile显式使用 float

java - 检查 Java 中的字母是否等于指定字母

python - Python 字典中的一个值可以有两个值吗?