Save data from a .txt [closed]

1

Good to everyone I have a question about how to save the data of a .txt that are in such a way:

Data 1

1.0  2.0
1.0  3.0
2.0  3.0

Elements 1

3.0 32.0
4.1 54. 6

Data 2

2.2 1.0
23.0 9.0
32.0 2.0

Go saving them in different matrices naming them with the name they have so that they remain so:

Datos1=[[1.0,2.0][1.0,3.0][2.0,3.0]]...

Thank you very much in advance.

    
asked by Antonio 26.09.2017 в 12:28
source

2 answers

0

you can do something like:

file = open('your_file.txt', 'r')
read_file = file.readlines()
file.close()

a = []

for i in range(len(read_file)):
    a.append(read_file[i].rstrip().split('  '))

print(a)

Here the first thing we do is open the file, then read the lines and close it, then create an empty list. The cycle what it does is read how many rows the file has, then add that line to the list a and with rstrip we eliminate the line break, with split we eliminate the 2 spaces it has between the 2 numbers, according to your example has 2 spaces, but the second example has only one.

It is already in your hands how to organize the rest, but it is the same code

    
answered by 26.09.2017 в 18:06
0

Here is my solution to your problem. I recommend that you do not try to change the name of a variable because it is unstable and it can be complicated.

# Recuperar datos de archivo
def openFile(ruta):
   data = open(ruta,"r")
   return data

# Guardar datos en una matriz
def formatData(data):
   matrix = []
   for line in data:
      matrix.append([float(x) for x in line.strip().split(" ")])
   return matrix

# ===================
# Algoritmo principal
def main():
   ruta = "Datos1.txt";
   data = openFile(ruta)
   matrix = formatData(data)

# Tu programa empieza aquí
if __name__ == '__main__':
    main()

I hope it serves you, regards

    
answered by 27.09.2017 в 12:28