1

I feel like I am lacking the terminology to properly search for answers to my question, so any hint in the right direction would be greatly appreciated.

I have a script that takes multiple (>30) user inputs to create a json file using a jinja2 template. It happens quite often that I need to add stuff both to the python code as well as the jinja2 template. For each change there are generally 4-5 different user inputs possible.

Rather than entering the >30 user inputs manually every time, I'd like to automate this. Is there a way to, for example, create a text file that lists the >30 user inputs and iterate over this file?

Example below:

    question1 = input('How much is 1+1?')
    question2 = input('Will I find an answer to my problem?')
    question3 = input('What should be the next question?')

Then the file with the answers would look like:

    2
    If you are lucky
    No idea

If at all possible, I would like to only have to do minimal modifications to the code.

3

1 Answer 1

1

You are looking for something like pickle or json. Json will be more legible should you choose to edit these in the text editor.

import json

answers = {'question1': 2, 'question2': 'If you are lucky'}
with open('answer_log.txt', 'w') as file:
    file.write(json.dumps(answers))

Then to load the file you call:

with open('answer_log.txt', 'r') as file:
    answers = json.loads(file.read())

This creates an easily editable text file that will look something like:

'{"question1": 2...........}'

Now you have a python dictionary you can easily iterate over to automate your process.

Sign up to request clarification or add additional context in comments.

1 Comment

.json is the traditional suffix for a JSON file, and it can be read with json.load(file), no need for loads(file.read())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.