Count line breaks in a file.txt with Python

1

I am doing a lexical analyzer for a class and one of the things that it must accomplish is to count the line breaks. How can I count the line breaks in Python from a text file? This is my code, am I using regular expressions?

**def newLine(linea):
count = 0
if re.match("\s",linea):
    count += 1
    #print("Salto de linea {0}".format(count))
else:
    pass

print ("Salto de linea totales en el archivo: {0}".format(count))
    
asked by Ladiv 12.12.2018 в 08:41
source

1 answer

2

You can count the number of line breaks by directly counting the number of lines. Here you have an example in which you define a string with 2 line breaks and then print the number of line breaks (number of lines -1):

linea = "Hola\nMundo\ncruel"

def newLine(linea):
    resultado=linea.splitlines()
    print(len(resultado)-1)

newLine(linea)
    
answered by 12.12.2018 / 09:37
source