用Python删除目录中的所有文件 [英] Deleting all files in a directory with Python

查看:121
本文介绍了用Python删除目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除目录中扩展名为 .bak 的所有文件。我怎么能在Python中做到这一点?

I want to delete all files with the extension .bak in a directory. How can I do that in Python?

os.listdir os.remove

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))

或者通过 glob.glob

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:
    os.remove(f)

请务必使用正确的目录,最终使用 os.chdir

Be sure to be in the correct directory, eventually using os.chdir.

这篇关于用Python删除目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆