Create temporary file in Python that will be deleted automatically after sometime

只谈情不闲聊 提交于 2021-01-04 02:31:24

问题


Is it possible to create temporary files in python that will be deleted after some time? I checked tempfile library which generates temporary files and directories.

tempfile.TemporaryFile : This function creates tempfile which will be destroyed as soon as closed.

tempfile.NamedTemporaryFile: This function accepts a parameter delete. If delete is given the value false while calling the function the file will not be deleted on close.

What I need is a temp file which I should be able to read with its name for some time even after I close it. However, It should be deleted automatically after some time.

What is the easiest way to do this in Python 2.7?


回答1:


If you only need to run the file at intervals within your Python program, you can use it as a context manager:

def main(file_object):
    # Can read and write to file_object at any time within this function

if __name__ == '__main__':
    with tempfile.NamedTemporaryFile() as file_object:
        main(file_object)
        # Can still use file_object
    # file_object is referencing a closed and deleted file here

If you need to be able to open it outside of the Python program, say after main is over, like in a process that runs asyncronously, you should probably look for a more permenant solution (e.g. allowing the user to specify the file name.)

If you really needed to have a temporary auto-deleting file, you can start a threading.Timer to delete it after some time, but make sure that your program deletes it even if it is stopped before the timer ends.



来源:https://stackoverflow.com/questions/44798879/create-temporary-file-in-python-that-will-be-deleted-automatically-after-sometim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!