0% found this document useful (0 votes)
10 views1 page

Python 2

Uploaded by

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

Python 2

Uploaded by

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

1.

Count the Number of Lines in a Text File


Python code
# Program to count the number of lines in a text file

# Open the file in read mode


with open("example.txt", "r") as file:
# Count the number of lines using len() on the list of lines
line_count = len(file.readlines())

print("Number of lines:", line_count)

This program opens the file in read mode, reads all lines, and uses len() to count the total
number of lines.

2. Count the Number of Words in a Text File


python code
# Program to count the number of words in a text file

# Open the file in read mode


with open("example.txt", "r") as file:
# Initialize word count to 0
word_count = 0

# Loop through each line in the file


for line in file:
# Split each line into words and count them
words = line.split()
word_count += len(words)

print("Number of words:", word_count)

This program reads each line, splits it into individual words using split(), and counts the
total words by summing up the length of each line's word list.

You might also like