[PYTHON] What to do when PermissionError of tempfile.mkstemp occurs

It's a basic thing, but since it fits a little, I recorded it as a memorandum

If you need a temporary file when writing a test etc. tempfile Is recommended.

tempfile.mkstemp () creates a temporary file, but you have to delete the file yourself. I thought I should do ʻos.remove () after the file operation, and as a result of writing and executing it, the PermissionError: [WinError 32] process cannot access the file. Another process is in use. :'C: \ ... [Temporary file path] `'error occurred.

As a result of trying various things while thinking that the with syntax is missing, it seems that the process at runtime still grabs the file, so I need to do ʻos.close ()`. did.

Below is an example of a test that worked well

class MyFileController():
    def __init__(self, path):
        self.path = path
    
    def output(self, data):
        with open(self.path, "a", newline='', encoding='utf_8_sig', errors='ignore') as f:
            f.write(data)   

class TestMyFileController(unittest.TestCase):
    def test_output(self):
        fd, path  = tempfile.mkstemp()
        mcc = MyFileController(path)
        try:
            mcc.output("test")

            with open(path, encoding='utf_8_sig') as f:
                test_data = f.read()
                self.assertEqual(headers, "test")

        finally:
            os.close(fd)          # <--Here.
            os.remove(path)

Recommended Posts

What to do when PermissionError of tempfile.mkstemp occurs
What to do when Ubuntu crashes
[python] What to do when an error occurs in send_keys of headless chrome
What to do when a Remove Error occurs when updating conda
[Beanstalk] What to do when an error occurs with import uuid
What to do when UnicodeDecodeError occurs during read_csv in pandas (pd.read_table ())
What to do when ModuleNotFoundError: No module named'XXX' occurs in Python
What to do if an error occurs when importing numpy with VScode
[OSX] [pyenv] What to do when an SSL error occurs in pip
Example of what to do when the sample script does not work (OpenCV-Python)
What to do if CERTIFICATE_VERIFY_FAILED occurs when nltk.download () is done on macOS pyhon
What to do when SSL error occurs in pip in Windows10, miniconda, VScode environment
[Go 1.13] What to do when unexpected directory layout: appears
[openpyxl] What to do when IllegalCharacterError appears in pandas.DataFrame.to_excel
curl: (60) What to do when Issuer certificate is invalid.
What to do when gdal_merge creates a huge file
What to do if a UnicodeDecodeError occurs in pip
What to do when "cannot import name xxx" [Python]
What to do when you can't bind CaboCha to Python
[Python] Type Error:'WebElement' object is not iterable What to do when an error occurs
[AWS] What to do when you want to pip with Lambda
What to do when Japanese is not displayed on matplotlib
What to do when PyCharm font is strange or garbled
What to do when Unalignable boolean Series provided as indexer
What to do if a 0xC0000005 error occurs in tf.train.start_queue_runners ()
What to do if package installation fails when deploying to heroku
What to do if a communication error occurs due to proxy when installing with package management of pip, npm, gem
What to do when "SSL: CERTIFICATE_VERIFY_FAILED _ssl.c: 1056" appears in Python
OSError: [Errno 40] What to do when Message too long appears
What to do when "Invalid HTTP_HOST header" appears in Django
ImportError: No module What to do when you are told
What to do when a Missing artifact occurs in a jar that is not defined in pom.xml
What to do when no display name occurs when unittesting Python + Tkinter on Github Actions Memo
What to do if ʻObject arrays cannot be loaded when allow_pickle = False` occurs in numpy.load ()
What to do if yum breaks
What to do with Magics install
What to do to get tensorflow-gpu to work
[AWS] What to do when the ping command causes a "timeout"
What to do when a video cannot be read by cv2.VideoCapture
What to do when the jupyterlab extension settings are not reflected
What to do if Insecure Platform Warning appears when running Python
What to do when you get "I can't see the site !!!!"
What to do when the value type is ambiguous in Python?
What to do when a part of the background image becomes transparent when the transparent image is combined with Pillow
What to do when the result downloaded via scrapy is in English
What to do when pyinstaller: error: argument --add-binary: invalid add_data_or_binary value: appears
[Docker] What to do when error Couldn't find the binary git appears
[Python] What to do when PEP8 is violated in the process of importing from the directory added to sys.path
What to do when "Something is already running at port 8000" is displayed when the develop command of Gatsby is executed.
[Python] What to do when an error related to SSL authentication is returned
[Django] What to do if an Integrity Error occurs when registering data from the management site to the database
What to do if fprintd requires a password when registering your fingerprint
What to do when the warning "The environment is in consistent ..." appears in the Anaconda environment
Notes on what to do when matplotlib scatter () / scatter3d () does not work
What to do if you get an error when installing Dlib (Ubuntu)
What to do after installing Linux (Ubuntu)
Let's summarize what you want to do.
What to do when psycopg2 throws an error when pipenv lock under Pipenv environment
What to do when a warning message is displayed in pip list
What to do if an error occurs when loading a python project created with poetry into VS Code
[Python] What to do if an error occurs in pip (pyinstaller, pyautogui, etc.)