Deleting files by type in Python on Windows

前端 未结 3 1454
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2021-01-18 03:08

    Here ya go:

    import os
    
    # Return all files in dir, and all its subdirectories, ending in pattern
    def gen_files(dir, pattern):
       for dirname, subdirs, files in os.walk(dir):
          for f in files:
             if f.endswith(pattern):
                yield os.path.join(dirname, f)
    
    
    # Remove all files in the current dir matching *.config
    for f in gen_files('.', '.config'):
       os.remove(f)
    

    Note also that gen_files can be easily rewritten to accept a tuple of patterns, since str.endswith accepts a tuple

    0 讨论(0)
  • 2021-01-18 03:11

    Use the glob module:

    import os
    from glob import glob
    
    for f in glob ('myfolder/*.config'):
       os.unlink (f)
    
    0 讨论(0)
提交回复
热议问题