Although the structure of your file is simple enough to be able to easily implement a loop that runs through it and processes it, since in a comment you admit that you can modify the format of the file, you would use a standard format for the one that has available automatic tools of parseo .
The typical formats used for configuration are JSON or YAML. We also have TOML, much less used, but that has won the favor of Python, since it will be the "official" format for the configuration of packages to be published in PyPi.
An example of how your configuration file would look with YAML:
servidores:
- dirServer: 10.0.0.3
usuario: Administrador
passwd: "##########"
- dirServer: 10.0.0.4
usuario: Administrador
passwd: "##########"
- dirServer: 10.0.0.5
usuario: Administrador
passwd: "#########"
To read that file you need to have installed the package pyyaml
( pip install pyyaml
), and the reading would be as simple as:
import yaml
with open("login.yaml") as f:
data = yaml.safe_read(f)
If you prefer the TOML format, the login.toml
file would have this structure:
[[servidores]]
dirServer = "10.0.0.3"
usuario = "Administrador"
passwd = "##########"
[[servidores]]
dirServer = "10.0.0.4"
usuario = "Administrador"
passwd = "##########"
[[servidores]]
dirServer = "10.0.0.5"
usuario = "Administrador"
passwd = "#########"
To read it is just as simple, but you need the package toml
( pip install toml
):
import toml
with open("conf.toml") as f:
data = toml.load(f)
Either of the two forms at the end gives you the same result in the variable data
. That variable will be a dictionary that will have the key "servidores"
, and within it the list with the information you need. So:
>>> print(data["servidores"])
[{'dirServer': '10.0.0.3', 'passwd': '##########', 'usuario': 'Administrador'},
{'dirServer': '10.0.0.4', 'passwd': '##########', 'usuario': 'Administrador'},
{'dirServer': '10.0.0.5', 'passwd': '#########', 'usuario': 'Administrador'}]
This is already processed with a loop as usual in python. For example:
for servidor in data["servidores"]:
conectarse(servidor["dirServer"], servidor["usuario"], servidor["passwd"])
Note The YAML format seems simpler when editing the configuration file by hand. However, reading YAML is more complicated than TOML (because, although in this example we are not using it, YAML has many more possibilities and much more flexibility, although in practice this power is almost never used).
The library to parse YAML takes up much more (and is slower) than TOML.