0% found this document useful (0 votes)
8 views2 pages

20

Uploaded by

Sirela Meena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

20

Uploaded by

Sirela Meena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

def count_file_content(file_path):

This line defines a function named count_file_content that takes one parameter,
file_path.
file_path is the path to the file whose content will be analyzed.

with open(file_path, 'r') as file:

This line opens the file specified by file_path in read mode ('r') and assigns
the file object to the variable file.
The with open(...): statement ensures that the file is properly closed after
the block of code is executed.

lines = file.readlines()

This line reads all the lines from the file and stores them in the list lines.
Each element in the lines list is a string representing a single line from the
file, including the newline character at the end of each line.

num_lines = len(lines)

This line calculates the number of lines in the file by finding the length of
the lines list.
num_lines stores the total count of lines.

num_words = sum(len(line.split()) for line in lines)

This line calculates the total number of words in the file.


line.split() splits each line into a list of words based on whitespace.
len(line.split()) gives the number of words in each line.
The sum(...) function adds up the number of words for all lines in the lines
list.
num_words stores the total count of words.

num_chars = sum(len(line) for line in lines)

This line calculates the total number of characters in the file.


len(line) gives the number of characters in each line, including spaces and
newline characters.
The sum(...) function adds up the number of characters for all lines in the
lines list.
num_chars stores the total count of characters.

print(f"Lines: {num_lines}")

This line prints the total number of lines in the file using an f-string to
format the output.

print(f"Words: {num_words}")

This line prints the total number of words in the file using an f-string to
format the output.

print(f"Characters: {num_chars}")

This line prints the total number of characters in the file using an f-string
to format the output.

count_file_content("input.txt")
This line calls the count_file_content function with "input.txt" as the
argument.
It opens the file input.txt, counts the number of lines, words, and characters,
and prints these counts to the console.

You might also like