Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
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
- Open the source file in read mode.
- Open the destination file in write mode.
- Read the source file line by line.
- For each line, check if it contains the character 'a' or 'A'.
- If the line does not contain 'a' or 'A', write it to the destination file.
- If the line contains 'a' or 'A', skip it (do not write to destination).
- Close both files.
- 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 closedMethod 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
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).
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.
What happens if the source file doesn't exist?
Python raises a FileNotFoundError. This should be handled using try-except blocks.
Why is it important to close files?
Closing files frees up system resources and ensures all data is properly written to the file.
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.
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.
What does strip() method do in file processing?
strip() removes leading and trailing whitespaces including newline characters from a string.
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.