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

Asked

Viewed 21,057 times

2

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

1,Janian,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]

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

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

3 answers

3


The file name you want to read is CSV (comma-separated values), meaning "comma separated values.

Picking up a file called 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

Upshot: resultado da execução do código

1

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)

Exit:

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

Output without the is optional

Basically the same thing

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

1

I will give an answer only for the conversion of the array, the other two responses of colleagues show how to read the file line by line. First, uses a function to convert the value to integer, if it fails, returns the string itself.

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

Using a for-comprehension, you can iterate on the values. Think of for-comprehension as a mathematical set.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.