Deleting files by type in Python on Windows

前端 未结 3 1453
时光说笑
时光说笑 2021-01-18 02:40

I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.

Say the directory is \\myfolder

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 03:08

    I would do something like the following:

    import os
    files = os.listdir("myfolder")
    for f in files:
      if not os.path.isdir(f) and ".config" in f:
        os.remove(f)
    

    It lists the files in a directory and if it's not a directory and the filename has ".config" anywhere in it, delete it. You'll either need to be in the same directory as myfolder, or give it the full path to the directory. If you need to do this recursively, I would use the os.walk function.

提交回复
热议问题