Strip And Split Read Lines In Python To Parse Config Files Effectively

Pavol Kutaj
1 min readDec 21, 2021

--

The aim of this pageđź“ť is to properly parse comma-separated values within a clients.txt the file of a script modifying Consul KV store with entries such as

<!-- CLIENTS.TXT -->
com_acme,dev1
...

…that end up as

<!-- RUN.PY RUNTIME -->
[["com_acme","dev1"],...]

…that is later on used to compose a URL which is the address of the key where a given value is stored in the Consul Database.

1. notes

  • instead of for loop, use list comprehension
  • .strip() removes " ", i.e. newline characters from the data structure
  • .split(",") creates 2 items within a subarray, the name, and the environment
  • use readlines() read each line of a file as a separate item
""" run.py """
with open("clients.txt", mode="rt", encoding="utf-8") as client_file:
clients_with_env = [line.strip().split(",")
for line in client_file.readlines()]

2. links

--

--

No responses yet