Python Program to Copy Lines Without the Letter 'a' to Another File
Intermediate · File handling · CBSE class 12 practical list
This program reads a text file and copies every line that does not contain the letter a into a second file, leaving behind the lines that do contain it. It is a CBSE class 12 practical question, usually worded as: remove all the lines that contain the character a in a file and write it to another file.
Program
Lines copied: 3 Contents of no_a.txt: Hello world Logic is the key Test your code often
How it works
- The program writes six sample lines to
notes.txt, and three of them contain the letter a. - A single
withstatement opens both files:notes.txtfor reading andno_a.txtfor writing. - For each line,
"a" not in lineis True only when the letter a appears nowhere in it, and those lines are written to the new file unchanged. - Lines read from a file keep their newline at the end, so
target.write(line)keeps them on separate lines in the new file. - Finally the program opens
no_a.txtagain and prints it, so you can see that only the three lines without an a were copied.
Another way to write it
Moving the lines with "a" out of the original file
Kept in notes.txt: ['Hello world', 'Logic is the key'] Moved to removed.txt: ['Python is easy to learn', 'Data is stored in files']
If your question says remove, this version takes the lines containing a out of notes.txt itself and saves them in removed.txt. Reading all the lines with readlines() first matters, because opening a file with "w" empties it straight away.
Try it yourself
Add the line "All OK" to the sample file and change the condition to "a" not in line.lower() so that lines with a capital A are left out too.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Display Lines Starting with T in a Text File
- Read a Text File and Separate Words with #
- Count Words in a Text File
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Count the Words "Me" and "My" in a Text File
- Read a File Line by Line
All Python programs · CBSE class 12 practical file · Python exercises