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.
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
Related Questions
Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character '#'.
Reading a file line by line from the beginning is a common task. What if you want to read a file backward ? This happens when you need to read log files. Write a program to read and display content of file from end to beginning.
Write a function Remove_Lowercase() that accepts two file names, and copies all lines that do not start with lowercase letter from the first file into the second file.
Write a program to display all the records in a file along with line/record number.