Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Use config parser to store run counter in a file

import configparser

config = configparser.ConfigParser()
config_fn = 'program.ini'

try:
    config.read(config_fn)
    run_counter = int(config.get('Main', 'run_counter'))
except configparser.NoSectionError:
    run_counter = 0
    config.add_section('Main')
    config.set('Main', 'run_counter', str(run_counter))
    with open(config_fn, 'w') as config_file:
        config.write(config_file)

run_counter += 1
print("Run counter {}".format(run_counter))
config.set('Main', 'run_counter', str(run_counter))
with open(config_fn, 'w') as config_file:
        config.write(config_file)

Solution 2:

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

Post a Comment for "Change Hardcoded Values In Python 3"