保存并能够加载 python 中的列表 3

Save and be able to load a list in python 3

我正在尝试在 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的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 同样容易,但您可以花时间添加一些功能,例如忽略空行,甚至可能包括应该忽略的注释语法。

#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)

鉴于您的用例,我认为使用 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