Counting Number of Lines in a File
Let’s take a look at how to find the number of lines in a file.
We'll cover the following
Counting lines based on a newline character
Previously, we learned how to count words from a file.
In this lesson, we’ll learn how to count the number of lines in a file using the split()
method on the newline character \n
.
A newline character is a code that tells the editor to insert a new line, a return. By counting the number of newline characters, we can get the number of lines in the program.
lines = data.split("\n")
print("The lines in the text are:")
print(lines)
Here, we’ll split the data at the new line, and then we print all the lines.
Add the above snippet of code in the code widget “Counting number of lines in Python” and we’ll see the following output when we click “Run:”
Get hands-on with 1200+ tech skills courses.