How to delete only the content of file in python

后端 未结 4 1349
無奈伤痛
無奈伤痛 2020-12-13 09:48

I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually arra

4条回答
  •  悲&欢浪女
    2020-12-13 10:17

    I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat contains:

    "This is the original content"
    

    Then you can simply write:

    f = open('myfile.dat', 'w')
    f.close()
    

    This would erase all the content. Then you can write the new content to the file:

    f = open('myfile.dat', 'w')
    f.write('This is the new content!')
    f.close()
    

提交回复
热议问题