Some Python Examples
← prev | next →     Top-level ToC     /config-files.html     (printable version)

There are a number of options.

1 config.py

You can create a module containing a hashmap that can serve as a config file:

cd my-proj
touch main.py config.py
chmod +x main.py

where config.py contains:

config = {
    'name': 'ringo',
    'speed': 13,
    'radius': 5,
}

and main.py contains:

#!/usr/bin/env python3

import config as c

print('speed is', c.config['speed'])

2 Customary-style config files

See the docs for configparser.

from configparser import ConfigParser
config = ConfigParser()
config.read('foo.ini')

That gives you something like a map of maps. That is, you can index into it like a map, but you can’t just print the whole thing out.

3 CSV

#!/usr/bin/env python3

import sys, csv

if len(sys.argv) != 3:
    print("""Please pass exactly 2 args: csv filename and x.

csv-foo.py foo.csv 3

Output will go to "out.csv".""")
    sys.exit()

def main():
    fnm = sys.argv[1]
    all_rows = read_in_csv(fnm) # A list of lists.

    x = sys.argv[2]

    header = all_rows[0]
    rows   = all_rows[1:]

    # Do stuff XXX

    with open("out.csv", 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows([header] + rows)

    print("Output written to ./out.csv.")


def read_in_csv(fnm):
    # Returns a list of lists (of strings).
    #
    # Why something like this isn't in Python's csv
    # module is ... left as an exercise for the reader.
    rows = []
    with open(fnm, newline='') as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            rows.append(row)
    return rows
    
# --------------------------------------------------
main()

4 EDN

Maybe have a look at https://github.com/swaroopch/edn_format.