I have a few zip files that I need to delete programmatically in Python 3. I do not need to open them first at all: I can determine if I want to delete them solely based on their filename. In scanning SO for this question, I note the following unsatisfactory questions (unsatisfactory, as in, I've tried all their approaches with no success):
- Removing path from a zip file using python
- Python zipfile doesn't release zip file
- Unable to remove zipped file after unzipping
- os.remove() in windows gives "[Error 32] being used by another process"
In particular, calling the close()
method or opening the file in a with
clause does not release whatever Windows lock there is. The simplest MWE I can dream up is this:
import os
file_path = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
os.remove(file_path)
This code produces:
PermissionError: [WinError 32] The process cannot access the file because it
is being used by another process: 'C:\\Users\\akeister\\Desktop\\Tatsuro
1.2.0.zip'
I get the same error if I try
import os
file_path = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
with open(file_path) as f:
f.close()
os.remove(file_path)
or
import gzip
import os
file_path = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
with gzip.GzipFile(file_path) as f:
f.close()
os.remove(file_path)
or
import zipfile
import os
zipped_file = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
with zipfile.ZipFile(zipped_file) as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
if not filename:
continue
source = zip_file.open(member)
os.remove(zipped_file)
There's no command prompt open to the desktop, and there's no Windows Explorer window open to the desktop.
I suspect part of my problem is that the files may be gzip files, and not regular zip files. I'm not entirely sure which they are. I generated the zip files (at least, they have a .zip extension) in LabVIEW 2015 using the built-in zip functions. It's not clear from the LabVIEW documentation which kind of compression the zip functions use.
What is the solution to my problem? Thanks in advance for your time!