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

Python Programs 03-10-2024

The document describes two Python programs: one that reverses the contents of a file and writes the result to another file, and another that counts the number of characters, words, and lines in a file. The first program uses string slicing to reverse the file content, while the second program utilizes a loop to read the file line by line and increment counters for characters, words, and lines. Both programs include sample code and expected output.

Uploaded by

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

Python Programs 03-10-2024

The document describes two Python programs: one that reverses the contents of a file and writes the result to another file, and another that counts the number of characters, words, and lines in a file. The first program uses string slicing to reverse the file content, while the second program utilizes a loop to read the file line by line and increment counters for characters, words, and lines. Both programs include sample code and expected output.

Uploaded by

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

Program to print each line of a file in reverse order

Theory:
1.Open the file using open
2.Read the file into a string using file.read
3.Reverse the string using slicing string[::-1]
4.Print the string

Program:
with open("FileReadDemo1.py", "r") as input1:
Data = input1.read()
rev = data[::-1]
a = open("Resultfile.txt", "w")
a.write(rev)
a.close()
print(" Reverse File contents are generated successfully ")

Output
Reverse File contents are generated successfully

Program to compute the number of characters, words,lines in a file


Theory:
1.)Open the file in read more using the open() Function
2.) Initialise variables to keep track of the character count , word count space count and line count
3.)Read the file line by line using a loop
4.) For each line , increment the count

5.) Increment the character count by the length of the line

Program:
f = open ('data.txt', mode ='r')
number_of_words =0
number_of_chars=0
number _of lines=0
for line in f:
number_of_lines+=1
line= line.strip("\n")
number_of_chars+=len(line)
list1= line.split()
number_of_words+=len(list1)
f.close()
print("number of lines:", number_of_lines)
print("number of words:",number_of_words)
print("number of characters:",number_of_chars)

Output:
number_of_lines=3
number_of_words=6
number_of_chars=35

You might also like