首页 > 解决方案 > 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()

标签: pythonpython-3.xlist

解决方案


问题是代码打开文件的方式:

with open(input_file, 'w') as file:

检查手册 - h​​ttps ://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()

推荐阅读