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由于“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()
点赞