[Python] Create a zip file that contains only files and not a folder/directory

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to create a function that lists the items of a directory and adds just the files in a zip folder (without having any folder inside the zip). So my directory looks like as follows:

    student_path
    student_1:
    file1.txt
    file2.txt
    file.html
    student_2:
    file1.txt
    file2.txt
    file.html
    ...
    student_n:
    file1.txt
    file2.txt


    I want to create a look through these folders that reads the files, deletes HTML files and zip only the text files of each student in a zip folder (but just the text files without any folder).

    My code for this is as follows:

    import os
    import shutil
    from zipfile import ZipFile, ZIP_DEFLATED
    import pathlib
    import pdb

    path = "assignment1/student_files/"
    folders = os.listdir(path)

    # Create a zip file from a directory
    def zipCreate(_path_, zip_path):

    folder = pathlib.Path(_path_)

    with ZipFile(zip_path, 'w', ZIP_DEFLATED) as zipf:
    for file in folder.iterdir():
    zipf.write(file, arcname=file.name)

    # Remove all python files from the student_files directory
    def remove_html(path):

    for item in folders:
    if not item == ".DS_Store":
    for file in os.listdir(path + item):
    if os.path.isdir(path + item + "/" + file):
    shutil.rmtree(path + item + "/__pycache__/")
    if file.endswith(".html"):
    print("Removing " + path + item + "/" + file)
    os.remove(path + item + "/" + file)


    # Create a zip file from the student_files directory
    zip_path = path + "/" + item + ".zip"
    zipCreate(path+item+"/", zip_path)

    if __name__ == "__main__":
    remove_html(path)
    print("Done removing python files and zipping submissions...")


    However, now each time I create a zip it is done under student_1 folder and I just would like to include the text files.

    Continue reading...

Compartilhe esta Página