How to delete the contents of a file before writing into it in a python script?
<p>I have a file called fName.txt in a directory. Running the following python snippet (coming from a simulation) would add 6 numbers into 3 rows and 2 columns into the text file through executing the loop (containing the snippet) three times. However, I would like to empty the file completely before writing new data into it. (Otherwise running the script for many times would produce more than three rows needed for the simulation which would produce nonsense results; in other words the script needs to <em>see</em> only three rows just produced from the simulation). I have come across the following page <a href="http://stackoverflow.com/questions/17126037/how-to-delete-only-the-content-of-file-in-python">how to delete only the contents of file in python</a>  where it explains how to do it but I am not able to implement it into my example. In particular, after <code>pass</code> statement, I am not sure of the order of statements given the fact that my file is closed to begin with and that it must be closed again once <code>print</code> statement is executed. Each time, I was receiving a different error message which I could not avoid in any case. Here is one sort of error I was receiving which indicated that the content is deleted (mostly likely after print statement):</p>

<blockquote>
  <p>/usr/lib/python3.4/site-packages/numpy/lib/npyio.py:1385: UserWarning: genfromtxt: Empty input file: "output/Images/MW_Size/covering_fractions.txt"
    warnings.warn('genfromtxt: Empty input file: "%s"' % fname)
  Traceback (most recent call last):
    File "Collector2.py", line 81, in 
      LLSs, DLAs = np.genfromtxt(r'output/Images/MW_Size/covering_fractions.txt', comments='#', usecols = (0,1), unpack=True)
  ValueError: need more than 0 values to unpack</p>
</blockquote>

<p>This is why I decided to leave the snippet in its simplest form without using any one of those suggestions in that page:</p>

<pre><code>covering_fraction_data = "output/Images/MW_Size/covering_fractions.txt"    
with open(covering_fraction_data,"mode") as fName:
        print('{:.2e} {:.2e}'.format(lls_number/grid_number, dla_number/grid_number), file=fName)
        fName.close()
</code></pre>

<p>Each run of the simulation produces 3 rows that should be printed into the file. When <code>mode</code> is 'a', the three produced lines are added to the existing file producing a text file that would contain more than three rows because it already included some contents. After changing 'a' to 'w', instead of having 3 rows printed in the text file, there is only 1 row printed; the first two rows are deleted unwantedly. </p>

<p><strong>Workaround:</strong></p>

<p>The only way around to avoid all this is to choose the 'a' <code>mode</code> and manually delete the contents of the file before running the code. This way, only three rows are produced in the text file after running the code which is what is expected from the output.</p>

<p><strong>Question:</strong></p>

<p>So, my question is basically, "how can I modify the above code to actually do the deletion of the file <em>automatically</em> and <em>before</em> it is filled with three new rows?"</p>

<p>Your help is greatly appreciated.</p>

<p>Using mode 'w' is able to delete the content of the file and overwrite the file but prevents the loop containing the above snippet from printing two more times to produce two more rows of data. In other words, using 'w' mode is not compatible with the code I have given the fact that it is supposed to print into the file three times (since the loop containing this snippet is executing three times). For this reason, I had to empty the file through the following command line inside the main.py code: </p>

<pre><code>os.system("&gt; output/Images/MW_Size/covering_fractions.txt")
</code></pre>

<p>And only then use the 'a' mode in the code snippet mentioned above. This way the loop is executing AND printing into the empty file three times as expected without deleting the first two rows.</p>

python python-3.x file-io seek