Class 12 Programs

Quick Tips

  • • Always use 'with' statement for file handling
  • • Handle file exceptions properly
  • • Consider case sensitivity in string operations

Remove all the lines that contain the character 'a' in a file and write it to another file

AIM

To remove all the lines that contain the character 'a' (both uppercase and lowercase) from a text file and write the remaining lines to another file.

ALGORITHM

  1. Open the source file in read mode.
  2. Open the destination file in write mode.
  3. Read the source file line by line.
  4. For each line, check if it contains the character 'a' or 'A'.
  5. If the line does not contain 'a' or 'A', write it to the destination file.
  6. If the line contains 'a' or 'A', skip it (do not write to destination).
  7. Close both files.
  8. Display appropriate messages about the operation.

PROGRAM

# Open source file in read mode and destination file in write mode
source_file = open("source.txt", "r")
destination_file = open("destination.txt", "w")

lines_removed = 0
lines_kept = 0

# Read the source file line by line
for line in source_file:
    # Check if line contains 'a' or 'A'
    if 'a' in line or 'A' in line:
        lines_removed += 1
        print(f"Removed line: {line.strip()}")
    else:
        # Write line to destination file if it doesn't contain 'a' or 'A'
        destination_file.write(line)
        lines_kept += 1

# Close both files
source_file.close()
destination_file.close()

print(f"\nOperation completed successfully!")
print(f"Lines kept: {lines_kept}")
print(f"Lines removed: {lines_removed}")
print("Check 'destination.txt' for the filtered content.")

Content of source.txt file:

Python is a programming language

It is easy to learn

Python supports multiple paradigms

Object-oriented programming

Functional programming

It has extensive libraries

Content of destination.txt file (after execution):

It is easy to learn

Object-oriented programming

Functional programming

OUTPUT

Removed line: Python is a programming language

Removed line: Python supports multiple paradigms

Removed line: It has extensive libraries

Operation completed successfully!

Lines kept: 3

Lines removed: 3

Check 'destination.txt' for the filtered content.

RESULT

Thus, the given program was successfully executed and the output was verified as per the expected result.

KEY POINTS

  • Case Sensitivity: The program checks for both 'a' and 'A' to handle case-insensitive matching
  • File Modes: Source file opened in 'r' mode, destination file in 'w' mode
  • Line Processing: Each line is processed individually using a for loop
  • Conditional Writing: Lines are written to destination only if they don't contain the target character
  • Statistics: Program keeps track of lines kept and removed for user feedback

PROGRAM VARIATIONS

Method 1: Using 'with' statement (Recommended)

# Using 'with' statement for better file handling
with open("source.txt", "r") as source, open("destination.txt", "w") as dest:
    lines_removed = 0
    lines_kept = 0
    
    for line in source:
        if 'a' not in line.lower():  # Case-insensitive check
            dest.write(line)
            lines_kept += 1
        else:
            lines_removed += 1
    
    print(f"Lines kept: {lines_kept}, Lines removed: {lines_removed}")
# Files are automatically closed

Method 2: Using list comprehension

# Reading all lines and filtering using list comprehension
with open("source.txt", "r") as source:
    lines = source.readlines()

# Filter lines that don't contain 'a' or 'A'
filtered_lines = [line for line in lines if 'a' not in line.lower()]

# Write filtered lines to destination
with open("destination.txt", "w") as dest:
    dest.writelines(filtered_lines)

print(f"Original lines: {len(lines)}")
print(f"Filtered lines: {len(filtered_lines)}")
print(f"Lines removed: {len(lines) - len(filtered_lines)}")

Method 3: Function-based approach

def remove_lines_with_character(source_file, dest_file, char):
    """Remove lines containing specified character from source to dest file"""
    try:
        with open(source_file, "r") as src, open(dest_file, "w") as dst:
            lines_kept = 0
            lines_removed = 0
            
            for line in src:
                if char.lower() not in line.lower():
                    dst.write(line)
                    lines_kept += 1
                else:
                    lines_removed += 1
            
            return lines_kept, lines_removed
    
    except FileNotFoundError:
        print(f"Error: {source_file} not found!")
        return 0, 0

# Call the function
kept, removed = remove_lines_with_character("source.txt", "destination.txt", "a")
print(f"Lines kept: {kept}, Lines removed: {removed}")

COMMON ERRORS & SOLUTIONS

FileNotFoundError

Make sure the source file exists in the same directory as your Python script.

Permission Error

Ensure you have write permissions for the destination file location.

Case Sensitivity Issues

Use .lower() method to make the search case-insensitive if needed.

VIVA QUESTIONS

  1. What is the difference between 'r' and 'w' file modes?

    'r' mode opens file for reading only, while 'w' mode opens file for writing (creates new file or overwrites existing).

  2. How do you make the character search case-insensitive?

    Use the .lower() method: if 'a' not in line.lower() to convert the line to lowercase before checking.

  3. What happens if the source file doesn't exist?

    Python raises a FileNotFoundError. This should be handled using try-except blocks.

  4. Why is it important to close files?

    Closing files frees up system resources and ensures all data is properly written to the file.

  5. What is the advantage of using 'with' statement?

    The 'with' statement automatically closes files even if an error occurs, making it safer for file operations.

  6. How can you modify this program to remove multiple characters?

    Use a list of characters and check if any character from the list is present in the line using any() function.

  7. What does strip() method do in file processing?

    strip() removes leading and trailing whitespaces including newline characters from a string.

  8. How would you count the total number of characters removed?

    Keep a counter for characters and increment it by len(line) for each line that contains the target character.