简体   繁体   English

在Windows上按Python类型删除文件

[英]Deleting files by type in Python on Windows

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 说目录是\\ myfolder

I want to delete all files that are .config files, but nothing to the other ones. 我想删除所有.config文件的文件,但没有删除其他文件。 How would I do this? 我该怎么做?

Thanks Kindly 谢谢你

Use the glob module: 使用glob模块:

import os
from glob import glob

for f in glob ('myfolder/*.config'):
   os.unlink (f)

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. 它列出了目录中的文件,如果它不是目录,文件名中包含“.config”,则将其删除。 You'll either need to be in the same directory as myfolder, or give it the full path to the directory. 您需要与myfolder位于同一目录中,或者为其提供目录的完整路径。 If you need to do this recursively, I would use the os.walk function . 如果你需要递归地执行此操作,我将使用os.walk 函数

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 还要注意gen_files可以很容易地重写以接受一个模式元组,因为str.endswith接受一个元组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM