gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:37:34 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com