How to delete only the content of file in python

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

    You can do this:

    def deleteContent(pfile):
        fn=pfile.name 
        pfile.close()
        return open(fn,'w')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 10:08

    How to delete only the content of file in python

    There is several ways of set the logical size of a file to 0, depending how you access that file:

    To empty an open file:

    def deleteContent(pfile):
        pfile.seek(0)
        pfile.truncate()
    

    To empty a open file whose file descriptor is known:

    def deleteContent(fd):
        os.ftruncate(fd, 0)
        os.lseek(fd, 0, os.SEEK_SET)
    

    To empty a closed file (whose name is known)

    def deleteContent(fName):
        with open(fName, "w"):
            pass
    



    I have a temporary file with some content [...] I need to reuse that file

    That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile and a context manager to almost transparently create/use/delete your temporary files:

    import tempfile
    
    with tempfile.TemporaryFile() as temp:
         # do whatever you want with `temp`
    
    # <- `tempfile` guarantees the file being both closed *and* deleted
    #     on exit of the context manager
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题