Tim
Tim

Reputation: 149

How to remove original file after unzipping it in python

I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use.

I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of the unzip action before removing the file?

file = zipfile.ZipFile(lfilename)
for filename in file.namelist():
    file.extract(filename,dir)
remove(lfilename)

Upvotes: 1

Views: 9716

Answers (3)

rkersh
rkersh

Reputation: 4465

The documentation for ZipFile says:

ZipFile is also a context manager and therefore supports the with statement.

So, I'd recommend doing the following:

with zipfile.ZipFile(lfilename) as file:
    file.extract(filename, dir)
remove(lfilename)

One advantage of using a with statement is that the file is closed automatically. It is also beautiful (short, concise, effective).

See also PEP 343.

Upvotes: 5

MotKohn
MotKohn

Reputation: 3965

You must first close the file.

    file.close()
    remove(lfilename)

Alternatively you could do the following:

with ZipFile('lfilename') as file:
    for filename in file.namelist():
        file.extract(filename,dir)
remove(lfilename)

Upvotes: 1

Shaun
Shaun

Reputation: 101

Try closing the file before removing it.

file = zipfile.ZipFile(lfilename)
for filename in file.namelist():
    file.extract(filename,dir)

file.close()

remove(lfilename)

Upvotes: 3

Related Questions