How can I read a txt file from a python file?

0

I need to go through a file and extract the values of the arrays to save them in some variables

the login.txt file which I need to go through has this structure:

# user=["dirServer","usuario","passwd","rutaServer","rutaDescarga","patron"]]

user1=["10.0.0.3","Root","*****","/usr/amat","C:\Users\becario2adm","yyyymmdd"]
user2=["10.0.0.4","Administrador","*******","/zzz","C:\Users\becario2adm","yyyy_mm_dd"]
user3=["10.0.0.5","Administrador","*******","/","C:\Users\becario2adm","yyyy_mm_dd"]


habia pensado leer ese fichero linea a linea con

while(mientras que la linea exista)
for linea in open('login.txt'):
    print (linea)
    
asked by antoniop 15.11.2018 в 09:10
source

1 answer

1

You do not have to complicate your existence by reinventing the wheel. There are already file formats to keep the information very similar to the one you propose.

For example, with a small syntax change in your login.txt file you can make it YAML valid. The only change needed is to use single quotes instead of doubles (to avoid having problems with the \ character that appears within some of your chains), and remove the assignments to user1 , user2 , etc. changing them by scripts.

That is, it is this way:

# Contenido del fichero login.txt
- ['10.0.0.3','Root','*****','/usr/amat','C:\Users\becario2adm','yyyymmdd']
- ['10.0.0.4','Administrador','*******','/zzz','C:\Users\becario2adm','yyyy_mm_dd']
- ['10.0.0.5','Administrador','*******','/','C:\Users\becario2adm','yyyy_mm_dd']

If you are willing to admit this entry format as valid, which I repeat is practically identical to the one you propose in the question, then you do not need to program a loop to read.

Just have the yaml library installed and do:

import yaml
with open("login.txt") as f:
  data = yaml.safe_load(f)

And that's it. In data you have a list with as many elements as lines had your file. Each item is another list whose elements are the ip, username, password, folder, etc.

For example, the following loop iterates over that list and shows the IP and the folder

for elemento in data:
  print(elemento[0], elemento[3])

and it comes out

10.0.0.3 /usr/amat
10.0.0.4 /zzz
10.0.0.5 /

I guess you will not find it difficult to adapt this code so that instead of printing these things on the screen, use them to make the ftp connections or whatever you want to do with that information.

    
answered by 15.11.2018 / 09:48
source