Problem with zipfile logic with Python

1

I'm trying to make a script with python to zip xls files. I've been able to get it into the directory and it's adding everything inside a .zip file. But I wanted it to go through all the subdirectories and only bring the .xls files and not the folders with the files.

Ex:

The path would be this:

  

C: / folder / subfolder / 201803

Inside the path I have numbered folders, eg:

  

C: / folder / subfolder / 201803/01

     

C: / folder / subfolder / 201803/02

and within those folders I have the .xls files.

xmlzip = zipfile.ZipFile(pathfile, 'w')
for folder, subfolder, files in os.walk(path):
    for file in files:
        if file.endswith('.xls'):
            xmlzip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder, file), path), compress_type = zipfile.ZIP_DEFLATED)
xmlzip.close()
    
asked by anonymous 20.05.2018 / 16:17

1 answer

1

To compress files without the directory structure, enter only the file name in the second parameter of the xmlzip.write method:

xmlzip = zipfile.ZipFile(pathfile, 'w')
for folder, subfolder, files in os.walk(path):
    for file in files:
        if file.endswith('.xls'):
            xmlzip.write(
                os.path.join(folder, file), 
                file, # AQUI => Informar apenas o nome do arquivo, sem o diretório
                compress_type = zipfile.ZIP_DEFLATED)
xmlzip.close()
    
20.05.2018 / 19:46