how to concisely create a temporary file that is a copy of another file in python

前端 未结 5 1396
孤城傲影
孤城傲影 2021-01-07 23:24

I know that it is possible to create a temporary file, and write the data of the file I wish to copy to it. I was just wondering if there was a function like:



        
5条回答
  •  执念已碎
    2021-01-07 23:28

    This isn't quite as concise, and I imagine there may be issues with exception safety, (e.g. what happens if 'original_path' doesn't exist, or the temporary_copy object goes out of scope while you have the file open) but this code adds a little RAII to the clean up. The difference here to using NamedTemporaryFile directly is that rather than ending up with a file object, you end up with a file, which is occasionally desirable (e.g. if you plan to call out to other code to read it, or some such.)

    import os,shutil,tempfile
    class temporary_copy(object):
    
        def __init__(self,original_path):
            self.original_path = original_path
    
        def __enter__(self):
            temp_dir = tempfile.gettempdir()
            base_path = os.path.basename(self.original_path)
            self.path = os.path.join(temp_dir,base_path)
            shutil.copy2(self.original_path, self.path)
            return self.path
    
        def __exit__(self,exc_type, exc_val, exc_tb):
            os.remove(self.path)
    

    in your code you'd write:

    with temporary_copy(path) as temporary_path_to_copy:
        ... do stuff with temporary_path_to_copy ...
    
    # Here in the code, the copy should now have been deleted.
    

提交回复
热议问题