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

Time:12-20

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

CodePudding user response:

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.

CodePudding user response:

Use ast.literal_eval with which you can safely evaluate an expression node or a string containing a Python literal or container display. Hence it will evluate your string as a proper list.

import ast

def build_sets(f):
    lista_valores = []
    with open(f, "r") as f:
      a = f.read().splitlines()

    for item in a:
      lista_valores.append(ast.literal_eval(item))
    print(lista_valores)

Output:

[[1, 'a', 'b'], [2, 'b', 'c']]

CodePudding user response:

thank you guys, i figured it out this way: lista_valores = []

with open(f, 'r') as f:
    for line in f:
        linha = line[0:len(line)-1].strip("[]").split(',')
        lista_valores.append(linha)


for i in range(len(lista_valores)): # convert to int
    for j in range(len(lista_valores[i])):
        if lista_valores[i][j].isdigit():
            lista_valores[i][j] = int(lista_valores[i][j])
  • Related