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.

David
  • 65
  • 2
  • 11
  • Possible duplicate of [How to supply stdin, files and environment variable inputs to Python unit tests?](https://stackoverflow.com/questions/2617057/how-to-supply-stdin-files-and-environment-variable-inputs-to-python-unit-tests) – tevemadar Sep 24 '19 at 22:59
  • Check the non-accepted answer with the mock library. Otherwise I just searched for ***python input test*** – tevemadar Sep 24 '19 at 23:01
  • [cookiecutter](https://cookiecutter.readthedocs.io/en/latest/) may be similar to what you're trying to make. – askaroni Sep 24 '19 at 23:30

1 Answers1

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.

Robert Kearns
  • 1,631
  • 1
  • 8
  • 15
  • `.json` is the traditional suffix for a JSON file, and it can be read with `json.load(file)`, no need for `loads(file.read())` – askaroni Sep 25 '19 at 02:39