How to Count the Number of Lines, Words, and Characters in a File Using Python?

Estimated read time 2 min read

You can count the number of lines, words, and characters in a file using Python by reading the file and processing its contents. Here’s an example:

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

# Initialize counters
line_count = 0
word_count = 0
char_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
        # Split the line into words
        words = line.split()
        # Increment word count
        word_count += len(words)
        # Increment character count (including newline character)
        char_count += len(line)
# Print the results
print(f"Number of lines: {line_count}")
print(f"Number of words: {word_count}")
print(f"Number of characters: {char_count}")

In this example, we first specify the file path of the file we want to process. 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 counters for lines, words, and characters accordingly. For words, we split each line using the split() method, which by default splits on whitespace characters, and then count the number of resulting words using len(). For characters, we simply count the length of each line using len(), which includes the newline character. Finally, we print the results using print() statements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply