How could I read a file.txt line by line and pass those values to a Python file?

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

datos = {}
busco = ['dirServer', 'usuario', 'passwd']

with open("login.txt") as fichero:
    for linea in fichero:
        trozos = linea.split(":")
        if trozos[0] in busco:
            datos[trozos[0]] = trozos[1].strip()

# Importa la clase FTP, necesaria para establecer una conexión, enviar y recibir datos.
from ftplib import FTP

# Se crea una instancia de dicha clase. Toma como argumentos host, user, passwd
ftp = FTP('dirServer')

# Hacemos el login de usuario y passwd, 
ftp.login(user='usuario', passwd='passwd')

# La función FTP.cwd() es utilizada para cambiar de directorio o carpeta
ftp.cwd("zzz") 

# Retorna información sobre los archivos y carpetas en la ubicación actual.
ftp.retrlines('LIST')

# Ejecuta el comando RETR para descargar el archivo README en modo binario.
# El segundo parámetro es una función callback que será llamada por cada bloque de bytes recibidos,
# que a su vez estos son pasados como argumento a dicha función. En este caso se pasa la función write de un objeto file
ftp.retrbinary('RETR prueba.txt', open('PruebaFtp.txt', 'wb').write)

ftp.quit()

How could you pass the value of ip, user, passwd from a file.txt?

fichero.txt
dirServer: 10.0.0.4
usuario: Administrador
passwd: **********

I get this series of errors

Traceback (most recent call last):
  File "C:\Users\becario2adm\My Documents\LiClipse 
Workspace\prueba2\prueba2.py", line 28, in <module>
ftp = FTP('dirServer')
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\ftplib.py", line 117, in __init__
self.connect(host)
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\ftplib.py", line 152, in connect
source_address=self.source_address)
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 707, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 748, in getaddrinfo
  for res in _socket.getaddrinfo(host, port, family, type, proto, flags):

socket.gaierror: [Errno 11001] getaddrinfo failed

    
asked by antoniop 25.10.2018 в 10:50
source

2 answers

4

If the file has only what you showed in the question (I do not know why I had initially understood that there were several users and passwords in the file), the thing is reduced to reading the lines and separating where the two are points.

Assuming that in addition to the server IP, the user name and password appear exactly in that order in the file, the thing is trivial:

with open("fichero.txt") as fichero:
  servidor = fichero.readline().split(":")[1].strip()
  usuario = fichero.readline().split(":")[1].strip()
  clave = fichero.readline().split(":")[1].strip()

ftp = FTP(servidor) 
ftp.login(user=usuario, passwd=clave)
ftp.cwd("zzz") 
ftp.retrlines('LIST')
ftp.retrbinary('RETR prueba.txt', open('PruebaFtp.txt', 'wb').write)
ftp.quit()

That is, once the file is opened, each time you use readline() it returns a line of it, on which we make .split(":") to separate it into two parts. This function returns a list with the found parts, and of them we are left with the second (element [1] of the list). On that value, which will be already a chain, we make strip() to eliminate the spaces that said chain may have in front or behind, and the new line character that will appear at the end of it.

As this solution is quite fragile (a change in the order of the lines of the file, or the existence of blank lines at the beginning or between the elements, would make the program stop working), I provide another approach.

Now it is a matter of having a list with the possible names of the data in which we are interested in the file, to compare each line read with those names and then extract the appropriate one, saving the values in a dictionary. Then we use that dictionary in the FTP connection:

datos = {}
busco = ['dirServer', 'usuario', 'passwd']

with open("fichero.txt") as fichero:
  for linea in fichero:
    trozos = linea.split(":")
    if trozos[0] in busco:
      datos[trozos[0]] = trozos[1].strip()

# Verificar que hemos encontrado toda la información que queríamo
# El diccionario debe tener tantas claves como las que buscaba
if len(datos) != len(busco):
  print("El fichero no tiene el formato esperado")
else:
  ftp = FTP(datos["dirServer"])
  ftp.login(user=datos["usuario"], passwd=datos["passwd"])
  ftp.cwd("zzz") 
  ftp.retrlines('LIST')
  ftp.retrbinary('RETR prueba.txt', open('PruebaFtp.txt', 'wb').write)
  ftp.quit()

Another possibility

If you can choose the format of the file with the data, the most correct (and simple, and flexible) would be to use a standard format that has good support in python. You could use JSON, but the current trend is to go to other languages easier to read / write by humans, such as YAML or TOML.

Specifically, TOML, although less known than others, is gaining strength to be preferred by many (for being very easy to parse). Your information stored in a TOML file looks like this:

dirServer = '192.68.1.1'
usuario = 'abulafia'
passwd = 'secreto                                     
answered by 25.10.2018 / 11:33
source
0

{} my code is like this:

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

data = {}

I search = ['dirServer', 'user', 'passwd']

with open("login.txt") as fichero:
for linea in fichero:
    trozos = linea.split(":")
    if trozos[0] in busco:
        datos[trozos[0]] = trozos[1].strip()

from ftplib import FTP
ftp = FTP('servidor') 
ftp.login(user='usuario', passwd='clave')
ftp.cwd("zzz") 
ftp.retrlines('LIST')
ftp.retrbinary('RETR prueba.txt', open('PruebaFtp.txt', 'wb').write)
ftp.quit()

I get this series of errors

 raceback (most recent call last):
  File "C:\Users\becario2adm\My Documents\LiClipse Workspace\prueba2\prueba2.py", line 30, in <module>
  ftp = FTP('servidor') 
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\ftplib.py", line 117, in __init__
self.connect(host)
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\ftplib.py", line 152, in connect
source_address=self.source_address)
 File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 707, in create_connection
  for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Users\becario2adm\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 748, in getaddrinfo
  for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
    
answered by 25.10.2018 в 12:06