python - 为什么我在运行程序时输入的前两个输入会在文本文件中重复?
问题描述
我正在尝试制作闪存卡生成器,但无法从文本文件中收集输入。当程序询问用户问题和答案时,它会将信息放入一个文本文件中,以便稍后在用户希望查看信息时使用。但是,每当程序第一次运行时,前两个输入在文本文件中重复两次。
这个错误的一个例子是这样的:
What is the capitol of New York, RochesterWhat is the Capitol of New York, Rochester .
这是我为完成任务而编写的代码:
user_inputs = []
f = open('flash_card.txt', 'a')
print('Hello! Welcome to Flash Card Study Helper:)')
create_add = input('Do you wish to create new cards? ')
while create_add == ('yes'):
question = input('Please type out the question: ')
answer = input('Please type out the answer: ')
combined = ','.join(user_inputs)
f.write(combined+'\n')
user_inputs.append(combined)
create_add =input('Do you wish to create another card? ')
else:
print(user_inputs)
为什么我的输入在写入文件时会重复?
解决方案
您正在跟踪 中的所有用户输入user_input
,然后每次通过循环将其写入您的文件。所以,第一次,你写 q1, a1。下一次,你写 q1, a1, q2, a2。下一次,你写 q1, a1, q2, a2, q3, a3。如果你真的想在每个循环中更新文件,你应该只写新的东西:
q_a = question + ',' + answer
f.write(q_a+'\n')
user_inputs.append(q_a)
推荐阅读
- sql - SQL 帮助 - 在当前记录时间戳之前查找顺序
- image - 如何在 react-native 中成功缓存最常用的数据(图像和文本)
- r - 在闪亮的 R 中显示来自网络的图像
- python - OSError: [Errno 1] 不允许操作
- go - Go中使用递归和并发的第N个斐波那契数
- python - 在使用 keras Lambda 时,如何处理“TypeError: Object arrays are not supported”?
- python - Python 给了我索引号而不是列表中的输入。
- swift - 敏感数据的 Vapor 3 GET 路由
- rest - 为 NFL api 生成访问令牌
- java - Java,获取与输入部分匹配的模式部分