[Tut] How to Delete a Line from a File in Python? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Delete a Line from a File in Python? (/thread-99982.html) |
[Tut] How to Delete a Line from a File in Python? - xSicKxBot - 09-24-2022 How to Delete a Line from a File in Python? <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"703098","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}"> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </div> <h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> This article will show you how to delete a line from a file in Python.</p> <p>To make it more interesting, we have the following running scenario:</p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>Rivers Clothing has a flat text file, <code>rivers_emps.txt</code> containing employee data. What happens if an employee leaves? They would like you to write code to resolve this issue.</em></p> <p><strong>Contents of rivers_emps.txt</strong></p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />102:Steve Markham<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to remove this line<em>?</em></p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p> <ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio"> <li><strong>Method </strong>1: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank"></a><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a></li> <li><strong>Method </strong>2: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing</a></li> <li><strong>Method </strong>3: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-write-a-numpy-array-to-a-text-file/" data-type="URL" data-id="https://blog.finxter.com/how-to-write-a-numpy-array-to-a-text-file/" target="_blank"><code>np.savetxt()</code></a>,</li> <li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-pop/" data-type="URL" data-id="https://blog.finxter.com/python-list-pop/" target="_blank"><code>pop()</code></a></li> <li><strong>Method 5</strong>: Use <code>remove()</code></li> <li><strong>Method 6</strong>: Remove row(s) from a DataFrame</li> </ul> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 1: Use List Comprehension</h2> <p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank"></a><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> to remove a specific line from a flat text file.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2,4-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre> <p>The above code uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> to read in the contents of a flat text file to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a>, <code>orig_lines</code>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>['100:Jane Smith', '101aniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', <br />'106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', <br />'109aul Paulson']</code></td> </tr> </tbody> </table> </figure> <p>Then, <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> is used again to append each element to a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> only if the element does <span style="text-decoration: underline">not </span>start with <strong>102</strong>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>['100:Jane Smith', '101aniel Williams', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109aul Paulson']</code></td> </tr> </tbody> </table> </figure> <p>As you can see, the element starting with <strong>102 </strong>has been removed. </p> <p>Next, a new file, <code>rivers_01.txt</code>, is opened in write (<code>w</code>) mode and the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> created above is written to the file with a <a href="https://blog.finxter.com/how-to-read-a-file-without-newlines/" data-type="post" data-id="24547" target="_blank" rel="noreferrer noopener">newline</a> (<code>\n</code>) character appended to each line. The contents of the file are shown below.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-delete-a-line-from-a-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaBC0VhpXkOQ%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 2: Use List Comprehension and Slicing</h2> <p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing</a> to remove a specific line from a flat text file.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2,4-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'.join(new_lines))</pre> <p>The above code uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> to read in the contents of a flat text file to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a>, <code>orig_lines</code>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>['100:Jane Smith', '101aniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109aul Paulson']</code></td> </tr> </tbody> </table> </figure> <p>Then <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing</a> is used to extract all elements, except element two (2). The results save to <code>new_lines</code>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <p>As you can see, element two (2) has been removed. </p> <p>Next, a new file, <code>rivers_02.txt</code>, is opened in write (<code>w</code>) mode and the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> created above is written to the file with a newline (<code>\n</code>) character appended to each line. The contents of the file are shown below.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-delete-a-line-from-a-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD2ZueuWXST8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 3: Use Slicing and np.savetxt()</h2> <p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing</a> and NumPy’s <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-write-a-numpy-array-to-a-text-file/" data-type="URL" data-id="https://blog.finxter.com/how-to-write-a-numpy-array-to-a-text-file/" target="_blank"><code>np.savetxt()</code></a> function to remove a specific line from a flat text file.</p> <p>Before moving forward, please ensure that the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-numpy-on-pycharm/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-numpy-on-pycharm/" target="_blank">NumPy</a> library is installed to ensure this code runs error-free. </p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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')</pre> <p>The first line imports the <a href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener"></a><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-numpy-on-pycharm/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-numpy-on-pycharm/" target="_blank">NumPy</a> library.</p> <p>The following line uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> to read the contents of a flat text file to the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a>, <code>orig_lines</code>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>['100:Jane Smith', '101aniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109aul Paulson']</code></td> </tr> </tbody> </table> </figure> <p>Then <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing</a> is applied to extract all elements, except element two (2). The results save to <code>new_lines</code>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <p>As you can see, element two (2) has been removed. </p> <p>The last code line calls <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-write-a-numpy-array-to-a-text-file/" data-type="URL" data-id="https://blog.finxter.com/how-to-write-a-numpy-array-to-a-text-file/" target="_blank"><code>np.savetxt()</code></a> and passes it three (3) arguments:</p> <ul> <li>The filename (‘<code>rivers_03.txt</code>‘.</li> <li>An iterable, in this case, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> (<code>new_lines</code>).</li> <li>A delimiter (appended to each line) – a newline character (<code>\n</code>).</li> <li>The <a href="https://blog.finxter.com/python-strings-format-specification-mini-language/" data-type="post" data-id="12462" target="_blank" rel="noreferrer noopener">format. Strings</a> are defined as <code>%s</code>.</li> </ul> <p>The contents of <code>rivers_03.txt</code> displays below.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-delete-a-line-from-a-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fs55BEAJRTOk%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 4: Use pop()</h2> <p class="has-global-color-8-background-color has-background">This example uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-pop/" data-type="URL" data-id="https://blog.finxter.com/python-list-pop/" target="_blank"><code>pop()</code></a> function to remove a specific line from a flat text file.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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')</pre> <p>The first line imports the <a href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy</a> library.</p> <p>The following line uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> to read in the contents of a flat text file to the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a>, <code>orig_lines</code>. If output to the terminal, the following displays.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>['100:Jane Smith', '101aniel Williams', '102:Steve Markham', '103:Howie Manson', '104:Wendy Wilson', '105:Anne McEvans', '106:Bev Doyle', '107:Hal Holden', '108:Mich Matthews', '109aul Paulson']</code></td> </tr> </tbody> </table> </figure> <p>Then, the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-pop/" data-type="URL" data-id="https://blog.finxter.com/python-list-pop/" target="_blank"><code>pop()</code></a> method is called and passed one (1) argument, the element’s index to remove.</p> <p>In this case, it is the second element. </p> <p>If this <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> was output to the terminal, the following would display.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <p>As shown in Method 3, the results save to a flat text file. In this case, <code>rivers_04.txt</code>. The contents are the same as in the previous examples.</p> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-delete-a-line-from-a-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fr9VhOWN5oEg%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-pop/" data-type="URL" data-id="https://blog.finxter.com/python-list-pop/" target="_blank"><code>pop()</code></a> function removes the appropriate index and returns the contents to capture if necessary.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 5: Use remove()</h2> <p class="has-global-color-8-background-color has-background">This example uses the <code><a href="https://blog.finxter.com/python-list-remove/" data-type="URL" data-id="https://blog.finxter.com/python-list-remove/" target="_blank" rel="noreferrer noopener">remove()</a> </code>function to remove a specific line from a flat text file.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np orig_lines = [line.strip() for line in open('rivers_emps.txt')] orig_lines.remove('102:Steve Markham') np.savetxt('rivers_05.txt', orig_lines, delimiter='\n', fmt='%s')</pre> <p>This code works exactly like the code in Method 4. However, instead of passing a location of the element to remove, this function requires the contents of the entire line you to remove.</p> <p>Then, the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-remove/" data-type="URL" data-id="https://blog.finxter.com/python-list-remove/" target="_blank">remove()</a></code> function is called and passed one (1) argument, the index to remove. In this case, it is the second element. If this <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> was output to the terminal, the following would display.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>100:Jane Smith<br />101aniel Williams<br />103:Howie Manson<br />104:Wendy Wilson<br />105:Anne McEvans<br />106:Bev Doyle<br />107:Hal Holden<br />108:Mich Matthews<br />109aul Paulson</code></td> </tr> </tbody> </table> </figure> <p>As shown in the previous examples, the results save to a flat text file. In this case, <code>rivers_05.txt</code>. </p> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-delete-a-line-from-a-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCjA4lX6cXKE%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Bonus: Remove row(s) from a DataFrame</h2> <p class="has-global-color-8-background-color has-background">CSV files are also known as flat-text files. This code shows you how to easily remove single or multiple rows from a CSV file</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd import numpy as np staff = { 'First' : ['Alice', 'Micah', 'James', 'Mark'], 'Last' : ['Smith', 'Jones', 'Watts', 'Hunter'], 'Rate' : [30, 40, 50, 37], 'Age' : [23, 29, 19, 45]} indexes=['FName', 'LName', 'Rate', 'Age'] df = pd.DataFrame(staff, index=indexes) df1 = df.drop(index=['Age']) df.to_csv('staff.csv', index=False)</pre> <p class="has-text-align-center has-base-2-color has-global-color-9-background-color has-text-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" />Finxter Challenge<br />Find 2 Additional Ways to Remove Lines</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Summary</h2> <p>This article has provided five (5) ways to delete a line from a file to select the best fit for your coding requirements.</p> <p>Good Luck & Happy Coding!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Programmer Humor – Blockchain</h2> <div class="wp-block-image"> <figure class="aligncenter size-full"><img loading="lazy" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uploads/2022/07/image-31-213x300.png 213w" sizes="(max-width: 280px) 100vw, 280px" /><figcaption><em>“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.”</em> <strong>source </strong> – <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure> </div></p> </div> https://www.sickgaming.net/blog/2022/09/23/how-to-delete-a-line-from-a-file-in-python/ |