'PermissionError: [WinError 32] when updating existing fits file
I'm working on win11 with python 3.9.7 and I'm trying to open a fits datacube that has different layers and append a new one and then save it, but when I do that, I get the following error: "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process"
This is an example of what I'm trying to do:
from astropy.io import fits
Datacube=fits.open(path2tile,memmap=False,mode='update')
Datacube.append(fits.ImageHDU(data=data,name='new layer'))
print(Datacube.info())
Datacube.writeto(path2tile,overwrite=True)
where path2tile is some path to the datacube I want to open and data is the new data I want to append to the existing datacube. I also tested different mode options but nothing works so far.
This is the output of the print statement:
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 4 ()
1 SCI 1 ImageHDU 8 (31, 31) float64
2 ERR 1 ImageHDU 8 (31, 31) float64
3 DQ 1 ImageHDU 8 (31, 31) float64
4 CRCELANSCI 1 ImageHDU 8 (31, 31) float32
5 NEW LAYER 1 ImageHDU 8 (31, 31) float32
So the new data is actually appended to the datacube, but for some reason, it can not be saved. The error is happening at the Datacube.writeto(path2tile,overwrite=True) line when it try to save the file. Anyone has any idea why this is happening and how can I fix it/bypass it?
Solution 1:[1]
To anyone looking for an answer to this problem, this is the solution I found:
from astropy.io import fits
Datacube=fits.open(path2tile,memmap=False,mode='update')
Datacube.append(fits.ImageHDU(data=data,name='new layer'))
print(Datacube.info())
Datacube.flush()
With the 'update' mode I just swapped the witeto() with flush() and it's working now. No more "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giovanni Maria Strampelli |
