traverse a file reading line by line with a stop condition

0

I have a login.txt file with this structure

DirServer
Usuario
Passwd
RutaDescarga
RutaServer
Patron
#
DirServer
Usuario
Passwd
RutaDescarga
RutaServer
Patron
#
DirServer
Usuario
Passwd
RutaDescarga
RutaServer
Patron

How can I go through the file line by line? How can you establish the     condition of reading up to #?

my code had it so because it only had one block

DirServer:
Usuario:
Passwd:
RutaDescarga:
RutaServer:
Patron:

with open("login.txt") as fichero:
    dirServer = fichero.readline().split(":")[1].strip()
    usuario = fichero.readline().split(":")[1].strip()
    passwd = fichero.readline().split(":")[1].strip()

And they have denied me cutting what comes behind: for possible failures and have changed my idea if my login.txt file is now like this

dirServer 10.0.0.3
usuario Administrador
passwd ##########
#
dirServer 10.0.0.4
usuario Administrador
passwd ##########
#
dirServer 10.0.0.5
usuario Administrador
passwd #########
#
    
asked by antoniop 14.11.2018 в 12:48
source

2 answers

0

You can use ConfigParser for configuration files, here's an example:

login.txt

[server_1]
dirServer = 10.0.0.4
usuario =Administrador
passwd =##########
[server_2]
dirServer=10.0.0.5
usuario=Administrador
passwd=#########

config.py

#!/usr/bin/python
from configparser import ConfigParser
def config_server(section='server_1' , filename='login.txt'):
    parser = ConfigParser()
    parser.read(filename)
    section_params = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            section_params[param[0]] = param[1]
    else:
        raise Exception('Seccion {0} no encontrada en el archivo{1}'.format(section, filename))

    return section_params

to obtain the parameters, just call it in the following way:

config_server() # retornara resultados server_1 en el archivo login.txt
config_server("server_2") # retornara resultados del server_2 en archivo login.txt
config_server("server_3" , "config.ini") # retornara resultados del server_3 en archivo config.ini

Another option is as follows:

#!/usr/bin/python
from configparser import ConfigParser
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp('login.txt')
config.get("server_1", "dirServer")
    
answered by 14.11.2018 / 13:34
source
1

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.

    
answered by 14.11.2018 в 13:06