Permission Denied To Write To My Temporary File

后端 未结 5 1210
广开言路
广开言路 2020-12-03 09:39

I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.

B

5条回答
  •  死守一世寂寞
    2020-12-03 10:32

    The following custom implementation of named temporary file is expanded on the original answer by Erik Aronesty:

    import os
    import tempfile
    
    
    class CustomNamedTemporaryFile:
        """
        This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:
    
        > Whether the name can be used to open the file a second time, while the named temporary file is still open,
        > varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
        """
        def __init__(self, mode='wb', delete=True):
            self._mode = mode
            self._delete = delete
    
        def __enter__(self):
            # Generate a random temporary file name
            file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
            # Ensure the file is created
            open(file_name, "x").close()
            # Open the file in the given mode
            self._tempFile = open(file_name, self._mode)
            return self._tempFile
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            self._tempFile.close()
            if self._delete:
                os.remove(self._tempFile.name)
    

提交回复
热议问题