How to delete only the content of file in python

后端 未结 4 1352
無奈伤痛
無奈伤痛 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:05

    What could be easier than something like this:

    import tempfile
    
    for i in range(400):
        with tempfile.TemporaryFile() as tf:
            for j in range(1000):
                tf.write('Line {} of file {}'.format(j,i))
    

    That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.

    Using tempfile is a lot better than trying to reinvent it.

提交回复
热议问题