read text file and generate lists for each line with element separation

0
  

In python, I have for example the following lines in a text file:

1, julian, 0.5,6,7,8,9

2, ana, 01,9,5,6,8,1

and wanted to generate lists:

list1 = [1, 'julian', 0.5,6,7,8,9]

list2 = [2, 'ana', 01,9,5,6,8,1]

  

Citation because I need to relate later through an equation the elements after the names so I needed to separate the elements.

    
asked by anonymous 05.06.2017 / 05:32

3 answers

2
  

The name of the file you want to read is comma-separated values (CSV), which means "comma-separated values."

Taking a file named meu.csv , with exactly this content:

1,julian,0,5,6,7,8,9
2,ana,01,9,5,6,8,1

You can pass this content to a list using the following code:

import csv
lista = [] # você só precisa de uma lista - ela é uma matriz multidimensional

with open('meu.csv', newline='') as csvfile:
    # o nome 'spamreader' abaixo é só exemplo, poderia ser qq. coisa
    spamreader = csv.reader(csvfile, delimiter=',') # separe por vírgula

    # o módulo csv detectará novas linhas automaticamente
    for linha in spamreader:
        lista.append(linha)

# os elementos começam ser contados em zero, i.e. lista[0][1] == 'julian'
print(lista[1]) # imprime a linha 2 da lista, inteira
print(lista[1][1]) # imprime apenas o segundo item da linha 2
  

Result:   

    
05.06.2017 / 06:25
0
f = open("texto.txt",'r')
texto = f.readlines()

x = 0

while x < len(texto):
    if texto[x] == "\n":
        local = texto.index(texto[x])
        texto.pop(local)
    else:
        texto[x] = texto[x].split(',')
        x += 1

# Esse for abaixo aqui é só para tirar o "\n" em algumas strings, é opcional.

for i in texto:
    local = texto.index(i) # Local do i em texto
    for b in i:
        local2 = texto[local].index(b) # Local2 do b em i ( local )
        if "\n" in b:
            texto[local][local2] = b.replace("\n",'') # Substitui o valor de acordo com "local" e "local2"

lista1, lista2 = texto
print("lista1 =",lista1)
print("lista2 =",lista2)

Output:

>>> lista1 = ['1', 'julian', '0', '5', '6', '7', '8', '9']
>>> lista2 = ['2', 'ana', '01', '9', '5', '6', '8', '1']

Exit without being optional

Basically the same thing

>>> lista1 = ['1', 'julian', '0', '5', '6', '7', '8', '9\n']
>>> lista2 = ['2', 'ana', '01', '9', '5', '6', '8', '1']
    
05.06.2017 / 07:22
0

I will give an answer only to the array conversion, the other two answers from colleagues show how to read the file line by line. First, use a function to convert the value to integer, if it does not, returns the string itself.

def converte(elem):
    try:
        int(elem)
    except:
        elem

Using a for-comprehension, it can iterate through values. Think of for-comprehension as a mathematical whole.

[converte(i) for i in string.split(linha, ',')]

This code could be written: "If i belongs to the set of elements that have been separated by commas, make a new set by applying the convert function."

    
05.06.2017 / 07:48