How to get a line count of a file in Python

Getting a line count of a file returns the number of nonempty lines in the file.

Solution for How to get a line count of a file in Python : You can use the in keyword to get a line count of a file Use open(file, mode) with the filename as file and “r” as mode to open a file and read its contents. Use a for-loop and the line in file syntax to check if line is nonempty. Increase line count by 1 each time line is nonempty. Use file.close() with the filename as file to close the file.

Use a list comprehension and str.strip() for a more compact implementation. Use len() to get the number of nonempty lines in the file.

file = open("sample.txt", "r")


how-to-get-a-line-count-of-a-file-in-python