python-3.xhardcode

Change hardcoded values in python 3


I would like to change hardcoded values in my code. I would like the code to replace and change hardcoded values based on the number of times it runs. Beginning with:

x=1

The next time, after I run it, in the code itself, I would like to see in the code editor:

x=2

It will automatically change the values of the code without human input, so the third time its run:

x=3

And this is all done just by the script running, no human interaction whatsoever. Is there an easy way?


Solution

  • You can simply write to a well-defined auxiliary file:

    # define storage file path based on script path (__file__)
    import os
    counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
    # start of script - read or initialise counter
    try:
        with open(counter_path, 'r') as count_in:
            counter = int(count_in.read())
    except FileNotFoundError:
        counter = 0
    
    print('counter =', counter)
    
    # end of script - write new counter
    with open(counter_path, 'w') as count_out:
            count_out.write(str(counter + 1))
    

    This will store an auxiliary file next to your script, which contains the counter verbatim.

     $ python3 test.py
     counter = 0
     $ python3 test.py
     counter = 1
     $ python3 test.py
     counter = 2
     $ cat my_counter
     3