In this article, you will learn how to count the number of lines in a text file in Python.
Count the Number of Lines in a Text File
You can count the number of lines in a text file using Python by opening the file and iterating through its lines, incrementing a counter for each line. Here’s an example code snippet:
file_path = "example.txt" # replace with your file path # open the file in read mode with open(file_path, 'r') as file: line_count = 0 # iterate through each line in the file for line in file: # increment the line count line_count += 1 # print the line count print("Number of lines:", line_count)
In this code snippet, we first specify the file path of the text file that we want to count the lines of. We then use the with statement to open the file in read mode and create a file object that we can use to read its contents.
We then initialize a line_count variable to zero, and use a for loop to iterate through each line in the file. For each line, we increment the line_count variable.
Finally, we print the value of line_count, which gives us the number of lines in the text file.