user3235542
user3235542

Reputation:

Extremely frustrating behavior with WindowsError (Error 32) to remove temporary files

I have to remove the tiff files extracted into temporary directory after completing the required tasks (reading, calculating, and resulting the outfile).

The following error attaching with one of the tiff files does not allow removing the files, and stops the program:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process 

Otherwise working code is as follows:

import os, glob, subprocess, gdal, numpy as np

files = glob.glob('*.txt')
temp_dir = 'E:\\td\\'

for r in files:

    fi = open (r, 'r')   
    files = fi.read().splitlines()
    winrar = 'C:\\Program Files\\WinRAR\\Rar.exe'
    extracts = [subprocess.call([winrar, 'x', f, temp_dir],shell=True) for f in files]
    fi.close()
    tiff_files = glob.glob(temp_dir + '*.tif')
    inrasters = [gdal.Open(i) for i in tiff_files] 

    data = np.array([e.GetRasterBand(1).ReadAsArray().astype(np.float32) for e in inrasters])
    data_mean = np.mean(data, axis=0)

    outdriver = gdal.GetDriverByName('GTiff')
    outraster = outdriver.Create('..\\outfile.tif',5000,5000,1,gdal.GDT_Float32)
    outraster.GetRasterBand(1).WriteArray(data_mean)

    inrasters, outraster  = None, None

    for x in tiff_files:
        os.remove(x)

Extremely frustrated because I could not figure out what the application is using that one file, and how to solve it. Any idea would be highly appreciated.

Upvotes: 1

Views: 1337

Answers (2)

Janne Karila
Janne Karila

Reputation: 25207

Try to add this before the delete loop:

 del e

Apparently the line inrasters, outraster = None, None is an attempt to close the files, but that only works if inrasters is the only reference to the files. The list comprehension that builds data leaves e as a reference to the last file.

Upvotes: 3

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

You need to close files before you can remove them. Close all open files before the last two lines.

Upvotes: 1

Related Questions