python - Python:创建/写入文件直到循环结束
问题描述
我正在尝试使用 Python 将用户输入的所有输入保存在文本文件中。我想确保输入的所有输入都存储在文件中,直到我完全退出程序,在这种情况下,直到我按“enter”停止列表。我还需要检查输入名称,看看它是否与之前的任何条目匹配。
我的程序现在的问题是,当我退出代码时,文本文件会更新输入的最新名称。我需要我的程序将所有这些名称保存在列表中,直到程序结束,因为我必须确保没有重复项。我将不得不警告用户该名称已经存在,我也需要帮助。我在下面的代码中创建了一个单独的函数,用于根据我的输入创建和编写文本文件,但我也注意到我可以在 get_people() 函数中实现它。我不确定为它创建新功能的最佳策略是什么。写文件肯定有问题。
文本文件应具有以下格式:
Taylor
Selena
Martha
Chris
下面是我的代码:
def get_people():
print("List names or <enter> to exit")
while True:
try:
user_input = input("Name: ")
if len(user_input) > 25:
raise ValueError
elif user_input == '':
return None
else:
input_file = 'listofnames.txt'
with open(input_file, 'a') as file:
file.write(user_input + '\n')
return user_input
except ValueError:
print("ValueError! ")
# def name_in_file(user_input):
# input_file = 'listofnames.txt'
# with open(input_file, 'w') as file:
# file.write(user_input + '\n')
# return user_input
def main():
while True:
try:
user_input = get_people()
# name_in_file(user_input)
if user_input == None:
break
except ValueError:
print("ValueError! ")
main()
解决方案
问题是代码打开文件的方式:
with open(input_file, 'w') as file:
检查手册 - https ://docs.python.org/3.7/library/functions.html?highlight=open#open代码会覆盖文件,open()
因为"w"
. 它需要打开它以追加 "a"
:
with open(input_file, 'a') as file:
如果文件不存在,追加将创建该文件,或追加到任何现有同名文件的末尾。
编辑:要检查您是否已经看过该名称,请将“已经看过”名称的列表传递给get_people()
函数,并将任何新名称也附加到该列表中。
def get_people( already_used ):
print("List names or <enter> to exit")
while True:
try:
user_input = input("Name: ")
lower_name = user_input.strip().lower()
if len(user_input) > 25:
raise ValueError
elif lower_name in already_used:
print("That Name has been used already")
elif user_input == '':
return None
else:
already_used.append( lower_name )
input_file = 'listofnames.txt'
with open(input_file, 'a') as file:
file.write(user_input + '\n')
return user_input
except ValueError:
print("ValueError! ")
def main():
already_used = []
while True:
try:
user_input = get_people( already_used )
# name_in_file(user_input)
if user_input == None:
break
except ValueError:
print("ValueError! ")
main()
推荐阅读
- node.js - 快速会话不断让我退出
- perl - 什么时候从 perl 中删除了 -P 选项?
- asp.net - ASP.NET Core - NLog - 如何禁用特定路由的日志记录?
- html - 我正在使用图片覆盖整个屏幕,但它没有覆盖,垂直滚动条显示,水平滚动条没有
- python - 我想使用 google smtp 服务器发送电子邮件。但它总是显示 SMTPAuthenticationError
- python - python字符串切片与交替步幅
- html - 在引导程序中与标签垂直对齐顶部显示文本
- excel - 如何使用循环在 TextBox 中添加数字
- javascript - 为什么在调用对类方法的引用时会丢失“this”引用
- iis - 如何使用 iis arr 中基于路径的路由为运行不同 iis 服务器的 2 个应用程序在 IIS 7.0 中配置应用程序请求路由