Search code examples
pythonpython-3.xpython-3.9

Save and be able to load a list in python 3


I'm trying to make a quiz maker and loader in python 3.9 and I'm wondering how do I save a list of questions and answers. This is so you can make a list then save it to a file and load it to answer it.

    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: "),
    ]

Solution

  • Given your usecase, I don't think it would be wise to use a pickle file. Instead I would suggest to convert the list into a string and store it in a simple txt file. Here is a sample of how you can do it:

    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