在Windows中使用Python按类型删除文件
我知道怎么删除单个文件,但我在实现删除某个类型的所有文件时感到困惑。
假设这个文件夹是 \myfolder。
我想删除所有的 .config 文件,但不想动其他类型的文件。我该怎么做呢?
谢谢!
3 个回答
1
给你看看:
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
可以接受一组模式。
5
我会做类似下面这样的事情:
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这个函数。
17
使用 glob
模块:
import os
from glob import glob
for f in glob ('myfolder/*.config'):
os.unlink (f)