Cilenco
Cilenco

Reputation: 7117

Python extract folder from zip file with spaces in name

Currently I'm writing a python script which extracts files from a zip file. For this I'm using the ZipFile module. Everything works great for files but I have a problem with folders which contains spaces in their name.

My zip file has following structure:

Test.zip
 - foo/test.txt
 - foo bar/test.txt

My code to extract the files looks like this:

currentFile = ZipFile(zipFilePath, 'r')

currentFile.extractall(path, 'foo/')
currentFile.extractall(path, 'foo bar/')

But the second call generates following error:

KeyError: "There is no item named 'b' in the archive"

I think this reffers to the 'b' of bar. So do you have any ideas why the second call does not work or how I should escape the space character in the folder name to extract it?

Upvotes: 2

Views: 2758

Answers (3)

FcoRodr
FcoRodr

Reputation: 1633

You have to pass the path within an array:

currentFile.extractall(path, ['foo bar/'])

Upvotes: 0

Cilenco
Cilenco

Reputation: 7117

Found the error by myself. From the documentation:

ZipFile.extractall([path[, members[, pwd]]])

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files.

Subset of the list referes back to a list. So I tried:

currentFile.extractall(path, ['foo bar/'])

and it worked great. Hope it will help someone. Also notice that path and members is reversed in comparison to the extract method!

Upvotes: 1

mac
mac

Reputation: 93

Try wrapping the path with r"string" instead of single quotes. Untested - just going from memory..

currentFile.extractall(r"foo bar/", path)

Upvotes: 0

Related Questions