[Python] Python zipfile and os

Discussão em 'Python' iniciado por Stack, Agosto 2, 2025.

  1. Stack

    Stack Membro Participativo

    I have some code to export all files within a zipfile to a path but what I want to do is create a new folder with the same name as the zipfile minus the ".zip" just like the windows explorer option does. I have commented out the code that doesn't work. It seems to be the os.makedirs that doesn't work.

    File "C:/Users/brentond/Documents/Python/Unzip all zip files in path.py", line 12
    Output = os.path.join(path, filename.replace(".zip", "")) # get new folder path name
    ^
    SyntaxError: invalid syntax


    the code:

    import os, zipfile

    # Define path of zip files to variable
    path = r'C:\Users\brentond\Documents\TA2\HA GDMS'

    for foldername, subfolders, filenames in os.walk(path): # walk directory
    for filename in filenames: # loop through files
    if filename.endswith(".zip"): # find zip files
    filepath = os.path.join(foldername, filename) # get zip file abs path
    #os.makedirs(os.path.join(path, filename.replace(".zip", "")) # create new folder same name as zip file
    #Output = os.path.join(path, filename.replace(".zip", "")) # get new folder path name
    ZipRef = zipfile.ZipFile(filepath) # create zip file object
    ZipRef.extractall(path) # extract all. This to put everything in the path folder
    #ZipRef.extractall(Output) # This to put the zip file contents into a folder with same name
    ZipRef.close() # close zip

    Continue reading...

Compartilhe esta Página