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

There are a number of options.


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

cd my-proj
chmod +x

where contains:

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

and 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()'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.


#!/usr/bin/env python3

import sys, csv

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

Output will go to "out.csv".""")

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:
    return rows
# --------------------------------------------------


Maybe have a look at