【问题标题】:Save and be able to load a list in python 3保存并能够在 python 3 中加载列表
【发布时间】:2021-05-10 03:09:58
【问题描述】:

我正在尝试在 python 3.9 中制作一个测验制作器和加载器,我想知道如何保存问题和答案列表。这样您就可以创建一个列表,然后将其保存到一个文件中并加载它来回答它。

    questions = [
        input("Enter question 1: "),
        input("Enter question 2: "),
        input("Enter question 3: "),
        input("Enter question 4: "),
        input("Enter question 5: "),
        input("Enter question 6: "),
        input("Enter question 7: "),
        input("Enter question 8: "),
        input("Enter question 9: "),
        input("Enter question 10: "),
    ]

【问题讨论】:

标签: python python-3.x python-3.9


【解决方案1】:

鉴于您的用例,我认为使用 pickle 文件并不明智。相反,我建议将list 转换为string 并将其存储在一个简单的txt 文件中。以下是您可以如何做到的示例:

questions = [
        input("Enter question 1: "),
        input("Enter question 2: "),
        input("Enter question 3: "),
        input("Enter question 4: "),
        input("Enter question 5: "),
        input("Enter question 6: "),
        input("Enter question 7: "),
        input("Enter question 8: "),
        input("Enter question 9: "),
        input("Enter question 10: "),
    ]

with open('outfile.txt','w') as f:
    f.write('SEP'.join(questions)) #You can replace the SEP with a newline or say a pipe operator (|) or something similar
    
with open('outfile.txt') as f:
    print(f.read().split("SEP")) #Returns the list of questions as you have earlier

【讨论】:

    【解决方案2】:

    python 的pickle 库通常是一个不错的选择,但它是一种人类无法读取的文件格式。如果您想方便地在简单的文本编辑器中打开问题列表,我建议您将问题列表简单地保存为 txt 文件中的行。您已经知道如何获取用户输入列表,因此您只需遍历该字符串列表,并将它们写入文件。

    #create a new txt file and open it in write mode
    with open(r"C:\some\file\path.txt", "w") as f: #use a 'raw' string to handle windows file paths more easily
        for question in questions:
            f.write(question + "\n") #add a newline to the end of the question so each question is on it's own line in the text file
    

    将文件读回到 python 中同样容易,但您可以花时间添加一些功能,例如忽略空白行,甚至可能包括应该忽略的 cmets 语法。

    #open the file in read mode
    questions = [] #create an empty list to read the questions into from the file
    with open(r"C:\some\file\path.txt", "r") as f:
        for line in f:
            if line.strip(): #if we strip whitespace from the front and back of a line is there any text left
                if not line.strip().startswith("#"): #if the first non whitespace character is a '#', treat the line as a comment and skip it
                    questions.append(line)
    

    【讨论】:

    • 如果是多行问题怎么办?为什么需要指定 'r' 读取模式,因为它是默认值。这个答案有很多陷阱和冗余!!另外,评论部分(#)...这是从哪里来的?
    • @paradocslover 我指定"r" 模式是为了让新程序员更清楚。可以省略。如果输入来自input(),则多行输入是不现实的,并且使用换行符作为分隔符使其更易于阅读。如果意图包括文件类型的人类可读性,并且期望用户可能使用文本编辑器,则很可能以额外的空白行结束。评论语法只是一个快速的想法,我必须花时间阅读我的答案来增加一些价值......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2018-08-17
    • 2017-04-20
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多