Python: Why am I getting a WinError 32?

python

Solution

You should close `inputFile` before trying to rename it :

...
    inputFile = open((x), "rb")
    byte1 = inputFile.read(1)
    byte2 = inputFile.read(1)
    inputFile.close()

Problem

I am writing some code that adds extensions to files depending on the header of the file. With any gzip files I am extracting the data. When I try and run the code I get a WinError 32. Below is the code and the error Thanks for any advice. ``` def extract(): os.chdir("C:/Users/David/MyFiles") files = os.listdir(".") for x in (files): inputFile = open((x), "rb") byte1 = inputFile.read(1) byte2 = inputFile.read(1) if byte1 == b'\x1f' and byte2 == b'\x8b': os.rename((x), (x) + ".gz") file = gzip.open((x), "rb") content = file.read() with open((x), "wb") as outputFile: outputFile.write(content) ``` Error: ``` PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'f_000002.gz' ```

Original source