[Python] Deleting files which starts with a name, searching in all subfolders [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    This code deletes files starting with a name, but it doesn't search beyond the primary folder, I need the code to search in all folders and subfolders inside the primary folder. I found this code in another question and works fine with primary folder but doesn´t search subfolders.

    import os, glob
    for filename in glob.glob("mypath/NAME*"):
    os.remove(filename)


    Tried insert

    import os, glob
    for root, dirs, files in os.walk(path):
    for filename in glob.glob("mypath/NAME*"):
    os.remove(filename)



    But nothing changed

    ALSO, I was suggested to a similar question (https://stackoverflow.com/questions/77843243/using-glob-to-find-all-csv-files-in-folder-and-subfolder-but-return-list-is-empt) suggesting the following code:

    import os
    from glob import glob
    #import pandas as pd


    all_files = []
    fdir = r"c:\Users\cubiculo7.imagen\Desktop\45"

    fnames = [os.path.basename(i)
    for i in glob(r"c:\Users\cubiculo7.imagen\Desktop\45\NAME*")
    ]

    #Get file names
    for fname in fnames:
    filename = os.path.join(fdir, fname)
    all_files.append(filename)
    os.remove(all_files)


    But does de same, only deletes files in folder, don´t search for subfolders and beyond

    Continue reading...

Compartilhe esta Página