LawfulEvil
LawfulEvil

Reputation: 2337

File lives on windows vs linux in Python 3.4

I have a script that I need to run on ubuntu and windows each using Python 3.4 and when I run on windows I get an exception, "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\me\Desktop\tmp9uvk57b4.txt'" while on linux, it works error free.

I've boiled down my problem to this example snippet. I'm not sure where the problem lies, but the snippet takes some text and writes it to a temporary file. After a while, it removes the temp file and that is where the error comes in.

#!/usr/bin/env python3

import os
import tempfile

msg = "THIS IS A HORRIBLE MESSAGE"

txt = None

try:

    txt = tempfile.mkstemp(dir='.', suffix='.txt')[1]
    with open(txt, "w") as f:
        f.write(msg)

except Exception as exp:
    raise exp

finally:
    if txt:
        os.remove(txt)

I assume there is some issue where windows doesn't close the file while linux does. Can I just explicitly close it again? Will that mess up anything on linux? Is there a good windows/linux gotcha resource?

Upvotes: 1

Views: 173

Answers (1)

Daniel
Daniel

Reputation: 42778

tempfile.mkstemp has two return values, an open filehandle and the filename. You don't use the open filehandle, such that it is never closed. Therefore the error message.

import os
import tempfile

msg = "THIS IS A HORRIBLE MESSAGE"

fd, filename = tempfile.mkstemp(dir='.', suffix='.txt')
try:
    with os.fdopen(fd, "w") as f:
        f.write(msg)
finally:
    os.remove(filename)

Upvotes: 3

Related Questions