Read multiple lines in a file in python

0

Hello friends I am creating a file with functions in python and I need to make a function that can add the whole numbers that contain the lines that are inside the file, I have managed to make me only read the first line with the function fichero.readline() but wanting to change it to readlines() throws me error

def crear_archivo(nombre):
    fichero = open(nombre,"w")
    fichero.close()

def escribir_fichero(nombre):
    fichero=open(nombre,"w")
    linea1= "1 a 2 b \n"
    fichero.write(linea1)
    linea2 = "3 c 4 d \n"
    fichero.write(linea2)
    fichero.close()

def muestra_pantalla(nombre):
    fichero=open(nombre, "r")
    linea = 0
    for i in fichero:
        print("Linea",str(linea),": ",str(i))
        linea = linea + 1
    fichero.close()

def suma_ficheros(nombre): #Esta seria la funcion
    fichero=open(nombre,"r")
    suma=0 #Creo la variable para guardar las sumas
    linea= fichero.readline() #SOlo puedo leer la primera linea
    lista = linea.split()'
    for x in lista:
        try:
            if isinstance(int(x), (int)):
                suma = suma + int(x)
        except Exception:
            print(x ,"Es una letra")
    print("La suma de los numeros es ", suma)

The output so far is this:

Linea 0 :  1 a 2 b 

Linea 1 :  3 c 4 d 

a Es una letra
b Es una letra
La suma de los numeros es  3
    
asked by Rebc3sp 25.05.2018 в 19:21
source

1 answer

1

If the point is to show, for each line of the file, the sum of the numbers on that line, the function could look like this:

def suma_fichero(nombre): 
    suma=0 #Creo la variable para guardar las sumas

    # Uso un contexto para abrir el fichero, así no se nos olvidará cerrarlo
    # (el contexto lo cerrará al salir del mismo)
    with open(nombre,"r") as fichero:
        for linea in fichero:
            # Cada línea se trocea y se procesa
            for x in linea.split():
                try:
                    # Simplifico. Si no es un entero, el siguiente int(x) 
                    # producirá excepción
                    suma = suma + int(x)
                except Exception:
                    print(x, "es una letra")
    print("La suma de los numeros es ", suma)
    
answered by 25.05.2018 / 20:32
source