The zipfile module is very interesting to manage .zip files with python.
However if the .zip file has been created on a linux system or macos the separator is of course '/' and if we try to work with this file on a Windows system there can be a problem because the separator is '\'. So, for example, if we try to determine the directory root compressed in the .zip file we can think to something like:
from zipfile import ZipFile, is_zipfile
import os
if is_zipfile(filename):
with ZipFile(filename, 'r') as zip_ref:
packages_name = [member.split(os.sep)[0] for member in zip_ref.namelist()
if (len(member.split(os.sep)) == 2 and not
member.split(os.sep)[-1])]
But in this case, we always get packet_name = [] because os.sep is "\" whereas since the compression was done on a linux system the paths are rather 'foo1/foo2'.
In order to manage all cases (compression on a linux system and use on a Windows system or the opposite), I want to use:
from zipfile import ZipFile, is_zipfile
import os
if is_zipfile(filename):
with ZipFile(filename, 'r') as zip_ref:
if all([True if '/' in el else
False for el in zip_ref.namelist()]):
packages_name = [member.split('/')[0] for member in zip_ref.namelist()
if (len(member.split('/')) == 2 and not
member.split('/')[-1])]
else:
packages_name = [member.split('\\')[0] for member in zip_ref.namelist()
if (len(member.split('\\')) == 2 and not
member.split('\\')[-1])]
What do you think of this? Is there a more direct or more pythonic way to do the job?