/ tech-note

How to use a config file in R and Python?

The easiest solution

The easiest solution would be just create a config.R (or something like that), and read the file in R.

For example here is config.R (replace <- with = in Python):

#file: config.R
user <- "root"
password <- "root"
host <- "localhost"
dbname <- "pokemon"

And then, read it by source("config.R") in R or from config import * in Python.

Generic solution compatible with other languages

However, if you want to share the config file with other languages, the solution above doesn't work any longer.

So to make the config more generic, use YAML. Much like any languages, both R and Python have a decent library to handle YAML file.

Here is a config.yml file:

year: 2017
 user: root
 password: root
 host : localhost
 name: pokemon

In R, use yaml package.

config <- yaml.load_file("config.yml")

class(config) # "list"
config$year # 2017
config$db$user # "root"

In Python, use PyYAML.

import yaml
with open("config.yml") as fp:
    config = yaml.safe_load(fp)

type(config) # dict
config["year"] # 2017
config["db"]["user"] # "root"