How to Count the Number of Lines in a Text File Using Python?

Estimated read time 1 min read

You can count the number of lines in a text file using Python by reading the file and counting the number of lines encountered. Here’s an example:

# Specify the file path
file_path = "/path/to/file.txt"

# Initialize line count
line_count = 0

# Open the file in read mode
with open(file_path, 'r') as file:
    # Iterate through each line in the file
    for line in file:
        # Increment line count
        line_count += 1
# Print the line count
print(f"Number of lines: {line_count}")

In this example, we first specify the file path of the file we want to count the lines for. Then, we open the file using the open() function in read mode, and use a with statement to automatically close the file after reading. We then iterate through each line in the file using a for loop, and increment the line_count variable by 1 for each line encountered. Finally, we print the line count using a print() statement.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply