Computer Science

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

Python Data Handling

2 Likes

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

Answered By

1 Like


Related Questions