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

Here’s a Python program that calculates the size of a file after removing end-of-line (EOL) characters, leading and trailing white spaces, and blank lines:

def calculate_file_size(filename):
    try:
        with open(filename, 'r') as file:
            modified_content = []

            for line in file:
                line = line.strip()  # Remove leading and trailing white spaces
                if line:  # Skip blank lines
                    modified_content.append(line)

            # Calculate the size of the modified content
            size = sum(len(line.encode()) for line in modified_content)

            return size

    except FileNotFoundError:
        print(f"File '{filename}' not found.")
        return None


filename = input("Enter the filename: ")
file_size = calculate_file_size(filename)

if file_size is not None:
    print(f"Size of the file (after modifications): {file_size} bytes")

 

When you run the program, it prompts you to enter the filename. You can provide the name of the file for which you want to calculate the size after modifications. The program opens the file in read mode and reads it line by line.

For each line, it removes the leading and trailing white spaces using strip(). If the line is not empty after removing white spaces, it appends the modified line to the modified_content list.

After processing all the lines, the program calculates the size of the modified content by encoding each line to bytes and summing their lengths using len().

Finally, the program displays the size of the file after modifications in bytes.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top