OSError Invalid argument when extracting with Python zipfile on Linux

Question:

I want to extract a file within a .zip archive to another directory. First I create a ZipFile object

  zfile = '/home/.../filename.zip'
  archive = zipfile.ZipFile(zfile, 'r')

The triple dot ... is me just hiding the full path, not there in the real path.

Then I extract a particular member from the archive to another directory

  print(archive.namelist()[0])    
  # returns sub\xxx.data where the two back slashes is not a typo!
  path = '/home/.../datadir'
  archive.extract(member='sub\xxx.data', path=path)

Then I get a system error

  OSError: [Errno 22] Invalid argument: '/home/.../datadir/sub\xxx.data'

If I manually change the two back slashes \ to one forward slash / then I get a different error

  archive.extract(member='sub/xxx.data', path=path)

  KeyError: "There is no item named 'sub/xxx.data' in the archive"

So the Linux system is not recognizing the path with two back slashes as a valid Linux path, and the path cannot be changed manually because then the file within the .zip archive is not recognized at all.

I get the same issue when using 7-Zip

Unfortunately I do not have any information or control regarding the method used to create the .zip file in the first place.

Asked By: Russell Burdt

||

Answers:

Linux recognises only '/' as a path separator, but you can set os.altsep = '\' which should work.

Answered By: mechanical_meat

Error 22 may also apply for a corrupt original zip file. Assure that your "filename.zip" file is a valid zip file.

Answered By: Renato Camargos

The answer by mechanical_meat and Russel Burdt is the correct approach, but in my case os.path.altsep= '\' was the solution.

Answered By: Agi