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