0

I try to do a python3 script and i have to delete all .xml in a folder. It's a giant folder with any folders in this folders (etc..).

(in dossier1, i have 2 folders and 2 .xml files, in there 2 folders, i have 2 folders and 2 .xml files etc)

Is it possible to say: "in this folder, search all the .xml and delete them" ?

i tried this:

filelist=os.listdir(path)
    for fichier in filelist[:]: # filelist[:] makes a copy of filelist.
        if not(fichier.endswith(".xml")):
            filelist.remove(fichier)

but python dont't go in differents folders.

Thanks for your help :)

guiguilecodeur
  • 429
  • 2
  • 15

2 Answers2

1

You can use pathlib.Path.glob:

>>> import pathlib
>>> list(pathlib.Path('.').glob("**/*.xml"))
[PosixPath('b.xml'), PosixPath('a.xml'), PosixPath('test/y.xml'), PosixPath('test/x.xml')]
>>> _[0].unlink() # delete some file
>>> for file in pathlib.Path('.').glob("**/*.xml"):
...   print(file)
...   file.unlink() # delete everything
... 
a.xml
test/y.xml
test/x.xml
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

You can use os.walk. This answer gives good info about it. You can do something like this

for path, directories, files in os.walk('./'): # change './' to directory path
      for file in files: 
           fname = os.path.join(path, file) 
           if fname.endswith('.xml'): # If file ends with .xml
               print(fname) 
               os.remove(os.path.abspath(fname))# Use absolute path to remove file

SajanGohil
  • 960
  • 13
  • 26