How to delete the contents of a file before writing into it in a python script?

前端 未结 2 855
时光说笑
时光说笑 2021-01-20 18:49

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 fi

2条回答
  •  深忆病人
    2021-01-20 19:30

    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:

    os.system("> output/Images/MW_Size/covering_fractions.txt")
    

    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.

提交回复
热议问题