[Tut] How to Erase Contents of a File - 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 Erase Contents of a File (/thread-99570.html) |
[Tut] How to Erase Contents of a File - xSicKxBot - 06-14-2022 How to Erase Contents of a File <div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"410360","slug":"default","valign":"top","reference":"auto","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})"}"> <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"> 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">In this article, you’ll learn how to erase the contents of a file in Python.</p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">To make it more fun, we have the following running scenario:</p> <p><em>Let’s say you have a Python script that retrieves the daily stock exchange prices for five (5) Tech Companies and saves it to <code>prices.txt</code>. To ensure no mistakes, you would like to erase the contents of this file before saving the latest data.</em></p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><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 erase the contents of a file?</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 1</strong>: Use <a href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/"><code>open()</code></a> and <a rel="noreferrer noopener" href="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" data-type="URL" data-id="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" target="_blank"><code>truncate(0)</code></a> </li> <li><strong>Method 2</strong>: Use <a href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/"><code>open()</code></a>, <code><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-modify-a-text-file-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-modify-a-text-file-in-python/" target="_blank">seek(0)</a></code> and <a rel="noreferrer noopener" href="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" data-type="URL" data-id="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" target="_blank"><code>truncate(0)</code></a></li> <li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/functions.html" data-type="URL" data-id="https://docs.python.org/3/library/functions.html" target="_blank"><code>with open()</code></a> </li> <li><strong>Method 4</strong>: Use <a href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/"><code>open()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/" target="_blank"><code>close()</code></a> on one line</li> <li><strong>Bonus</strong>: Extract Characters and Erase Remainder</li> </ul> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Preparation</h2> <p>To follow along, copy, paste and save the text below to<code> prices.txt</code>. Move this file to the current working directory.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td>AAPL,138.22<br />MMSF,255.67<br />HPE,14.51<br />DELL,14.51<br />MNDT,21.89</td> </tr> </tbody> </table> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 1: Use open() and truncate()</h2> <p class="has-global-color-8-background-color has-background">This method erases the contents of a file without removing the file itself using <a href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/"><code>open()</code></a> and <a rel="noreferrer noopener" href="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" data-type="URL" data-id="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" target="_blank"><code>truncate(0)</code></a>.</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="">fp = open('prices.txt', 'w') fp.truncate(0) fp.close()</pre> <p>This code opens <code>prices.txt</code> in write mode (<code>w</code>) and saves the output to <code>fp</code> which creates a file object similar to the output below.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code><_io.TextIOWrapper name='prices.txt' mode='w' encoding='cp1252'></code></td> </tr> </tbody> </table> </figure> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4e2.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Tip:</strong> A file object is returned whenever a file is opened in Python. This object allows access to process/manipulate the open file.</p> <p>Next, <code>fp.truncate(0)</code> is called. This method resizes the said file to a specified number of bytes. If no argument is passed, the current file position is used.</p> <p>Finally, <code>fp.close()</code> is called to close the open file.</p> <p>If this code is successful, an empty <code>prices.txt</code> file now resides in the current working directory.</p> <figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <iframe loading="lazy" title="Python open() Function -- An 80/20 Guide by Example" width="780" height="439" src="https://www.youtube.com/embed/so9MlRnUG1Y?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 2: Use open(), seek(0) and truncate(0) </h2> <p class="has-global-color-8-background-color has-background">This method opens/re-opens a file and erases the contents without removing the file itself using <a href="https://blog.finxter.com/python-open-function/"><code>open()</code></a>, <code><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-modify-a-text-file-in-python/" target="_blank">seek()</a></code> and <a rel="noreferrer noopener" href="https://python-reference.readthedocs.io/en/latest/docs/file/truncate.html" target="_blank"><code>truncate(0)</code></a>.</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="">fp = open('prices.txt', 'r+') fp.seek(0) fp.truncate() </pre> <p>This code opens/re-opens the <code>prices.txt</code> file in <em>read/write</em> mode (<code>r+</code>) and saves the output to <code>fp</code> which creates a file object similar to the output above.</p> <p>Next, <code>fp.seek(0)</code> is called to re-position the file pointer (<code>fp</code>) to a given position in the file. In this case, the position is <code>0</code> (the top of the file).</p> <p>Then, <code>fp.truncate(0)</code> is called. This method resizes the said file to a specified number of bytes. If no argument is passed, the current file position is used.</p> <p>If this code is successful, an empty <code>prices.txt</code> file now resides in the current working directory.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 3: Use with open()</h2> <p class="has-global-color-8-background-color has-background">This method erases the contents of a file without deleting the file itself using <code><code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/functions.html" data-type="URL" data-id="https://docs.python.org/3/library/functions.html" target="_blank">with open()</a></code></code> on <a href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">one-line</a>!</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">with open('prices.txt', 'w'): pass</pre> <p>This code calls <code><a href="https://docs.python.org/3/library/functions.html" data-type="URL" data-id="https://docs.python.org/3/library/functions.html" target="_blank" rel="noreferrer noopener">with open()</a></code> to open <code>prices.txt</code> for writing (<code>w</code>). Then, the <code>pass </code>statement executes, which does nothing, and the file automatically closes.</p> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4e2.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Tip:</strong> The <code>pass</code> statement is used as a placeholder. When <code>pass</code> executes, nothing happens. This is necessary when code is expected, but no code is required. </p> <p>If this code is successful, an empty <code>prices.txt</code> file now resides in the current working directory.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 4: Use open() and close() on one line</h2> <p class="has-global-color-8-background-color has-background">Also a good option, this method opens a file for writing (<code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/functions.html" data-type="URL" data-id="https://docs.python.org/3/library/functions.html" target="_blank">open()</a></code>) and closes said file (<a rel="noreferrer noopener" href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/" target="_blank"><code>close()</code></a>) using one line of code!</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">open('prices.txt', 'w').close()</pre> <p>This code uses <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/functions.html" data-type="URL" data-id="https://docs.python.org/3/library/functions.html" target="_blank">open()</a></code> to open <code>prices.txt</code> for writing (<code>w</code>). Since no other code is called, the file contents are erased, and the file closes (<a rel="noreferrer noopener" href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/" target="_blank"><code>close()</code></a>).</p> <p>If this code is successful, an empty <code>prices.txt</code> file now resides in the current working directory.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Bonus: Erase File Contents after Specified Location</h2> <p class="has-global-color-8-background-color has-background">What happens if you want to erase everything after the first x number of characters in a file and return the same? </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 os fp = os.open('prices.txt', os.O_RDWR|os.O_CREAT) os.ftruncate(fp, 4) os.lseek(fp, 0, 0) str = os.read(fp, 100).decode('utf-8') print(f"Read String is : {str}") os.close(fp)</pre> <p>This example could be used for erasing the entire contents of a file. However, let’s retrieve the first four (4) characters from <code>prices.txt</code> (AAPL) and erase the remainder.</p> <p>First, this code calls in the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/os.html" data-type="URL" data-id="https://docs.python.org/3/library/os.html" target="_blank"><code>os</code></a> library to access the many functions available for interacting with the <a href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="post" data-id="19050" target="_blank" rel="noreferrer noopener">operating system</a>. </p> <p>Then, <code>prices.txt</code> is opened in <em>read/write</em> mode, and if the file does not exist, or fails, a new file is created (<code>os.O_RDWR|os.O_CREAT)</code>).</p> <p>Then, the file is truncated to 4 bytes/characters (<code>os.ftruncate(fp, 4)</code>) and the file pointer (<code>fp</code>) moves to the top of the file (<code>os.lseek(fp, 0, 0)</code>).</p> <p>Next, the code reads in the first four (4) bytes/characters indicated above and decodes the output (<code>os.read(fp, 100).decode('utf-8')</code>) and saves to <code>str</code>.</p> <p>The output is sent to the terminal, and the file closes.</p> <p><strong>Output</strong></p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>Read String is: AAPL</code></td> </tr> </tbody> </table> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Summary</h2> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">These four (4) methods of how to erase the contents of a file should give you enough information to select the best one for your coding requirements.</p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Good Luck & Happy Coding!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Programmer Humor</h2> <p class="has-global-color-8-background-color has-background"><em>There are only 10 kinds of people in this world: those who know binary and those who don’t.<br /></em><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f469.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f9d4-200d-2642-fe0f.png" alt="?♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" /><em><br />~~~</p> <p>There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary.</em> <em><br /></em><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f469.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f9d4-200d-2642-fe0f.png" alt="?♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f471-200d-2640-fe0f.png" alt="?♀️" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> </p> </p> </p></p> </div> https://www.sickgaming.net/blog/2022/06/10/how-to-erase-contents-of-a-file/ |