Problem with Python zipfile logic

Asked

Viewed 198 times

1

I’m trying to make a python script to zip xls files. I managed to get it inside directory and is adding everything inside a file .zip. However I wanted it to go through all subdirectories and be able to bring only the . xls files and not the folders with the files.

Ex:

The path would be that:

C:/Folder/subfolder/201803

Inside the path I have numbering folders, e.g.:

C:/Folder/subfolder/201803/01

C:/Folder/subfolder/201803/02

and inside these 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()

1 answer

1


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

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()
  • 1

    Perfect friend. Thank you very much, I had already tested several ways and it had not worked. I think I missed understand the same structure. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.