How to count the number of lines and characters in a file using Python?

To count the number of lines and characters in a file, you can use the following code:

def count_lines_characters(filename):
    lines = 0
    characters = 0

    with open(filename, 'r') as file:
        for line in file:
            lines += 1
            characters += len(line)

    return lines, characters

filename = 'example.txt'
lines, characters = count_lines_characters(filename)
print("文件行数:", lines)
print("文件字符数:", characters)

In the code above, the function count_lines_characters takes a file name as a parameter and then opens the file using the open function. By iterating through each line of the file, we can use the len function to calculate the number of characters in each line and add them to the characters variable. We also use a variable lines to keep track of the number of lines. Finally, we return the number of lines and characters.

You can change the file name example.txt to the actual file name you want to count.

广告
Closing in 10 seconds
bannerAds