Skip to main content

How to count the number of lines in a file in Python

How to count the number of lines in a file in Python.

Here's a step-by-step tutorial on how to count the number of lines in a file using Python:

Step 1: Open the file To begin, you need to open the file in Python. You can do this using the built-in open() function. The open() function takes two parameters: the file path and the mode (read, write, append, etc.). In this case, we only need to read the file, so we'll use the "r" mode.

file_path = "path/to/file.txt"
file = open(file_path, "r")

Step 2: Read the file Next, you need to read the contents of the file. You can do this using the readlines() method, which reads all the lines in the file and returns them as a list.

lines = file.readlines()

Step 3: Count the lines Once you have the lines stored in a list, you can simply use the len() function to determine the number of lines in the file.

num_lines = len(lines)

Step 4: Close the file After you have finished reading the file, it's good practice to close it using the close() method. This will free up system resources and ensure that the file is properly closed.

file.close()

Step 5: Display the result Finally, you can display the number of lines in the file by printing it to the console.

print("Number of lines in the file:", num_lines)

Complete code example:

file_path = "path/to/file.txt"
file = open(file_path, "r")
lines = file.readlines()
num_lines = len(lines)
file.close()
print("Number of lines in the file:", num_lines)

That's it! You now have a complete Python program to count the number of lines in a file. Just replace "path/to/file.txt" with the actual path to your file, and you're good to go.