Skip to content
Advertisement

Reading files from python and adding to a list with correct value type

I am reading a file in python and i need to add every line to a list. The problem is that every line is a list containing string and integers. This is the file i am reading: file

this is the output of reading the file and putting it on the new list. output

as you can see it is storing me the lines as a string but it need to be like this: correct output

CODE:

def build_sets(f):
   
    lista_valores = []

    with open(f, 'r') as f:
        for line in f:
            lista_valores += line.strip().split('n')

    print(lista_valores)
    #pass

Advertisement

Answer

Try this in your for loop:

lista_valores = line.strip('][').split(', ')

Also please only use english words to define your variables, it’s one of the main rules of variable naming conventions.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement