Python Program That Reads a Text File but Delete Lines That Starts With
Because Python provides no direct method for deleting a specific line in a file, it'due south necessary to find our own arroyo.
In this guide, we'll embrace several ways of removing lines from a text file using Python. We'll run across how to remove lines based on their position in the document and how to delete content that matches a string.
We'll also cover examples of using custom logic to tackle more challenging problems. Information technology doesn't thing if we're working with a simple text file, or more complicated comma-separated files (CSV), these techniques will help you lot manage your data.
Nosotros tin employ Python to handle both large and small files in a memory efficient manner.
Using a Number to Delete a Line
In our first example, we'll wait at removing a line based on it's position in the file. Starting with a randomly generated list of names saved on our computer, we'll use Python to delete a name from the list based on the order it appears in the list.
The file is called names.txt and it's saved in the same directory as our python file. Our goal is to delete the 7th line in the file.
In Python, nosotros can apply the with argument to safely open up files. With the file open, we'll employ the readlines() method to recollect a list containing the file's contents.
That'south all for reading the list of names. Next, nosotros'll use some other with statement to open the file again, this time in write fashion.
Using a for loop to iterate over the lines of the file, nosotros also make utilise of a variable to continue track of the current line number. When we reach the line we desire to remove, an if statement makes sure nosotros skip the line.
Allow's become over the steps one more time:
- Open the file in read mode
- Read the files contents
- Open the file in write style
- Utilise a for loop to read each line and write information technology to the file
- When we reach the line we want to delete, skip it
Because we're using a Python with statement to handle the file, there'due south no need to shut it after we're done. Python takes care of that for us.
names.txt
1 Amina,Waelchi
two Sharon Reynolds
three Lilian Hane
4 Felicita Howell
five Sallie Senger
6 Lucile Schuster
seven Emmitt Schuppe
8 Rowena Leffler
9 Hipolito Batz
ten Gia Hill
Example one: Remove a line based on a specified line number
def remove_line(fileName,lineToSkip): """ Removes a given line from a file """ with open up(fileName,'r') as read_file: lines = read_file.readlines() currentLine = 1 with open(fileName,'westward') as write_file: for line in lines: if currentLine == lineToSkip: pass else: write_file.write(line) currentLine += 1 # call the part, passing the file and line to skip remove_line("names.txt",7)
By wrapping our logic in a function, nosotros tin easily remove a line from a file by calling remove_lines() and passing the name of the file and the number of the line nosotros'd like to remove.
If we plan to use a block of Python lawmaking more than than once, information technology's a adept idea to wrap it in a role. Doing so will save us time and energy.
Delete a Line past Matching Content
We've seen how to remove content from a file based on its line position. Now we'll look at how to delete a line that matches a given cord.
We have a catalogue of plant nursery rhymes, but someone has played a bit of mischief on us. In an ironic stroke, they've added the line "This line doesn't belong" to our files!
There'south no need to panic. Nosotros can use Python to easily undo the mischief.
In our Python code, we'll start by reading the file, named itsy_bitsy.txt, and storing its content in a variable called lines.
But like in the previous example, we'll use Python with statements to open the file. In order to find the matching line, we'll need to remove the newline characters that readlines() tacks on to the end of every string.
We can remove the newline character using the strip() function. This is a built-in office that removes characters from the beginning or end of a string.
When the matched content is found, we'll use an if argument to pass it over, effectively removing it from the old file.
itsy_bitsy.txt
The itsy bitsy spider climbed up the waterspout.
Down came the rain
And washed the spider out.
Out came the lord's day
This line doesn't belong
And dried upwardly all the rain
And the itsy bitsy spider climbed upwards the spout again.
Case 2: Matching content and removing information technology from a file
with open up("itsy_bitsy.txt", 'r') as file: lines = file.readlines() # delete matching content content = "This line doesn't belong" with open("itsy_bitsy.txt", 'w') equally file: for line in lines: # readlines() includes a newline character if line.strip("\due north") != content: file.write(line)
Using Custom Logic to Delete a Line in Python
When dealing with file data, we'll often need custom tailored solutions to encounter our needs. In the following examples, we'll explore using custom logic to solve a diverseness of information problems.
Past tailoring our solutions, it's possible to solve more difficult bug. For example, what if we'd like to delete a line from a file, but only know office of information technology?
Even if we only know a single word, we can use Python to notice the line we need to remove. By taking advantage of Python's built-in methods, nosotros'll run into how to solve custom challenges with Python code.
Remove a line with a specific string
In the side by side exercise, we'll encounter how to remove a line that contains a function of a string. Building on the knowledge gained from the previous examples, it's possible to delete a line containing a given substring.
In Python, the notice() method tin can be used to search a string for a substring. If the string contains the substring, the function returns an index representing its position. Otherwise, the method returns -ane.
In a text file named statements.txt, nosotros have a list of randomly generated sentences. Nosotros demand to remove any sentence that contains the given substring.
By using find(), we'll know if a line contains the string we're looking for. If it does, we'll remove it from the file.
Hither'southward the syntax for using observe():
mystring.notice(substring)
statements.txt
He didn't heed the warning about the banana.
My friend took the apples to the market.
She bought a farm that grows peaches.
There is a lovely grape orchard beyond the hills.
She'south absolutely nuts about her new car.
Case 3: Delete a line that contains a given string
# remove a line containing a string with open("statements.txt",'r') as file: lines = file.readlines() with open("statements.txt",'west') equally file: for line in lines: # discover() returns -one if no friction match is plant if line.find("nuts") != -ane: pass else: file.write(line)
Remove the shortest line in file
Allow's take another look at statement.txt. Some changes have been fabricated.
statements.txt
He didn't listen the warning about the Banana.
My friend took the apples to the market.
She bought a farm that grows peaches.
He claims to have seen a UFO.
There is a lovely grape orchard beyond the hills.
There was petty to eat on the island besides coconuts.
Nosotros've added some new lines. This time, we need to remove the shortest line in the certificate. We tin can exercise this by using the len() method to find the length of each line.
Past comparing the lengths of the lines, it's possible to find the shortest line. Afterwards, we can apply a with statement open and remove the line from the file.
Example 4: Delete the shortest line in a file using the len() method
# remove the shortest line from statements.txt with open("statements.txt",'r') as read_file: lines = read_file.readlines() shortest = 1000 # used to compare line length lineToDelete = "" # the line we want to remove for line in lines: if len(line) < shortest: shortest = len(line) lineToDelete = line with open("statements.txt",'due west') as write_file: for line in lines: if line == lineToDelete: pass else: write_file.write(line)
Summary
With this postal service we've covered several methods of deleting lines from files in Python. We saw that nosotros can delete lines based on their position in a file using a for loop.
Nosotros tin can likewise remove files that lucifer content by comparing strings, either with the == operator, or by using the discover() method.
These are only some of the ways one can remove lines from a file in Python.
Related Posts
If you'd like to learn more about working with strings and file data in Python, follow the links below.
- Joining string with Python string chain
- How to use a Python dictionary for better data management
- Using Python list comprehension to streamline your code
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real earth applications and principal the basics.
Source: https://www.pythonforbeginners.com/files/how-to-delete-a-specific-line-in-a-file
Post a Comment for "Python Program That Reads a Text File but Delete Lines That Starts With"