CBSE Class 12 Computer Science Question 92 of 136

Data File Handling — Question 31

Back to all questions
31
Question

Question 31

Write a Python program to display the size of a file after removing EOL characters, leading and trailing white spaces and blank lines.

Answer

Let the file "sample.txt" include the following sample text:

  The sky is blue\n 
  
  Clouds float gently in the sky.   
  
  Birds sing sweet melodies.   
file = open('sample.txt', 'r')
lines = file.readlines()
original_size = 0
for line in lines:
    original_size += len(line)
print("Original file size:", original_size)
file.close()

file = open('sample.txt', 'r')
cleaned_size = 0
for line in file:
    cleaned_line = line.strip()
    if cleaned_line:
        cleaned_size += len(cleaned_line)
file.close()
print("Cleaned file size:", cleaned_size)
Output
Original file size: 126
Cleaned file size: 74