Downside Formulation and Resolution Overview
To make it extra fascinating, we’ve got the next operating situation:
Contents of rivers_emps.txt
100:Jane Smith |
Methodology 1: Use Checklist Comprehension
This instance makes use of Checklist Comprehension to take away a selected line from a flat textual content file.
orig_lines = [line.strip() for line in open('rivers_emps.txt')] new_lines = [l for l in orig_lines if not l.startswith('102')] with open('rivers_01.txt', 'w') as fp: print(*new_lines, sep='n', file=fp)
The above code makes use of Checklist Comprehension to learn within the contents of a flat textual content file to a Checklist, orig_lines
. If output to the terminal, the next shows.
['100:Jane Smith', '101:Daniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', |
Then, Checklist Comprehension is used once more to append every aspect to a brand new Checklist provided that the aspect does not begin with 102. If output to the terminal, the next shows.
['100:Jane Smith', '101:Daniel Williams', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109:Paul Paulson'] |
As you possibly can see, the aspect beginning with 102 has been eliminated.
Subsequent, a brand new file, rivers_01.txt
, is opened in write (w
) mode and the Checklist created above is written to the file with a newline (n
) character appended to every line. The contents of the file are proven beneath.
100:Jane Smith |
Methodology 2: Use Checklist Comprehension and Slicing
This instance makes use of Checklist Comprehension and Slicing to take away a selected line from a flat textual content file.
orig_lines = [line.strip() for line in open('rivers_emps.txt')] new_lines = orig_lines[0:2] + orig_lines[3:] with open('rivers_02.txt', 'w') as fp: fp.write('n'.be a part of(new_lines))
The above code makes use of Checklist Comprehension to learn within the contents of a flat textual content file to a Checklist, orig_lines
. If output to the terminal, the next shows.
['100:Jane Smith', '101:Daniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109:Paul Paulson'] |
Then Slicing is used to extract all parts, besides aspect two (2). The outcomes save to new_lines
. If output to the terminal, the next shows.
100:Jane Smith |
As you possibly can see, aspect two (2) has been eliminated.
Subsequent, a brand new file, rivers_02.txt
, is opened in write (w
) mode and the Checklist created above is written to the file with a newline (n
) character appended to every line. The contents of the file are proven beneath.
100:Jane Smith |
Methodology 3: Use Slicing and np.savetxt()
This instance makes use of Checklist Comprehension, Slicing and NumPy’s np.savetxt()
operate to take away a selected line from a flat textual content file.
Earlier than transferring ahead, please be sure that the NumPy library is put in to make sure this code runs error-free.
import numpy as np orig_lines = [line.strip() for line in open('rivers_emps.txt')] new_lines = orig_lines[0:2] + orig_lines[3:] np.savetxt('rivers_03.txt', new_lines, delimiter="n", fmt="%s")
The primary line imports the NumPy library.
The next line makes use of Checklist Comprehension to learn the contents of a flat textual content file to the Checklist, orig_lines
. If output to the terminal, the next shows.
['100:Jane Smith', '101:Daniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109:Paul Paulson'] |
Then Slicing is utilized to extract all parts, besides aspect two (2). The outcomes save to new_lines
. If output to the terminal, the next shows.
100:Jane Smith |
As you possibly can see, aspect two (2) has been eliminated.
The final code line calls np.savetxt()
and passes it three (3) arguments:
- The filename (‘
rivers_03.txt
‘). - An iterable, on this case, a Checklist (
new_lines
). - A delimiter (appended to every line) – a newline character (
n
). - The format. Strings are outlined as
%s
.
The contents of rivers_03.txt
shows beneath.
100:Jane Smith |
Methodology 4: Use pop()
This instance makes use of the pop()
operate to take away a selected line from a flat textual content file.
import numpy as np orig_lines = [line.strip() for line in open('rivers_emps.txt')] orig_lines.pop(2) np.savetxt('rivers_04.txt', orig_lines, delimiter="n", fmt="%s")
The primary line imports the NumPy library.
The next line makes use of Checklist Comprehension to learn within the contents of a flat textual content file to the Checklist, orig_lines
. If output to the terminal, the next shows.
['100:Jane Smith', '101:Daniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109:Paul Paulson'] |
Then, the pop()
technique known as and handed one (1) argument, the aspect’s index to take away.
On this case, it’s the second aspect.
If this Checklist was output to the terminal, the next would show.
100:Jane Smith |
As proven in Methodology 3, the outcomes save to a flat textual content file. On this case, rivers_04.txt
. The contents are the identical as within the earlier examples.
💡Observe: The pop()
operate removes the suitable index and returns the contents to seize if mandatory.
Methodology 5: Use take away()
This instance makes use of the take away()
operate to take away a selected line from a flat textual content file.
import numpy as np orig_lines = [line.strip() for line in open('rivers_emps.txt')] orig_lines.take away('102:Steve Markham') np.savetxt('rivers_05.txt', orig_lines, delimiter="n", fmt="%s")
This code works precisely just like the code in Methodology 4. Nevertheless, as an alternative of passing a location of the aspect to take away, this operate requires the contents of your complete line you to take away.
Then, the take away()
operate known as and handed one (1) argument, the index to take away. On this case, it’s the second aspect. If this Checklist was output to the terminal, the next would show.
100:Jane Smith |
As proven within the earlier examples, the outcomes save to a flat textual content file. On this case, rivers_05.txt
.
Bonus: Take away row(s) from a DataFrame
CSV information are also referred to as flat-text information. This code reveals you the right way to simply take away single or a number of rows from a CSV file
import pandas as pd import numpy as np employees = { 'First' : ['Alice', 'Micah', 'James', 'Mark'], 'Final' : ['Smith', 'Jones', 'Watts', 'Hunter'], 'Charge' : [30, 40, 50, 37], 'Age' : [23, 29, 19, 45]} indexes=['FName', 'LName', 'Rate', 'Age'] df = pd.DataFrame(employees, index=indexes) df1 = df.drop(index=['Age']) df.to_csv('employees.csv', index=False)
✨Finxter Problem
Discover 2 Further Methods to Take away Traces
Abstract
This text has offered 5 (5) methods to delete a line from a file to pick one of the best match on your coding necessities.
Good Luck & Comfortable Coding!
Programmer Humor – Blockchain


At college, I discovered my love of writing and coding. Each of which I used to be in a position to make use of in my profession.
Through the previous 15 years, I’ve held numerous positions akin to:
In-house Company Technical Author for numerous software program applications akin to Navision and Microsoft CRM
Company Coach (employees of 30+)
Programming Teacher
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder