繁体   English   中英

在Windows上按Python类型删除文件

[英]Deleting files by type in Python on Windows

我知道如何删除单个文件,但是我在如何删除一个类型的目录中的所有文件的实现中丢失了。

说目录是\\ myfolder

我想删除所有.config文件的文件,但没有删除其他文件。 我该怎么做?

谢谢你

使用glob模块:

import os
from glob import glob

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

我会做类似以下的事情:

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

它列出了目录中的文件,如果它不是目录,文件名中包含“.config”,则将其删除。 您需要与myfolder位于同一目录中,或者为其提供目录的完整路径。 如果你需要递归地执行此操作,我将使用os.walk 函数

你走了:

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)

还要注意gen_files可以很容易地重写以接受一个模式元组,因为str.endswith接受一个元组

暂无
暂无

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

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