使用Python删除目录中的所有文件

slh*_*080 141 python file-io

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

mik*_*iku 251

通过os.listdiros.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))
Run Code Online (Sandbox Code Playgroud)

或者通过glob.glob:

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:
    os.remove(f)
Run Code Online (Sandbox Code Playgroud)

一定要在正确的目录中,最终使用os.chdir.

  • 您的第一个示例是使用冗余for循环.你可以使用 - [os.remove(f)for os in os.listdir(".")if f.endswith(".bak")] - 因为要使用列表推导.或者你可以将理解中的'if'移动到for循环中 - 对于os.listdir(".")中的f:if f.endswith(".bak"):os.remove(f) (19认同)
  • 注意os.listdir(".")!!! 我用这个代码忘了改变路径,我所有的代码都消失了!尝试了两种不同的工具来恢复,但没有运气! (5认同)
  • @dragonjujo,是的,我知道,但我认为这样会更清楚.. (4认同)

unu*_*tbu 24

使用os.chdir更改目录.使用glob.glob以生成结束它".bak的"文件名列表.列表的元素只是字符串.

然后你可以os.unlink用来删除文件.(PS.os.unlink并且os.remove是同一功能的同义词.)

#!/usr/bin/env python
import glob
import os
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
    os.unlink(filename)
Run Code Online (Sandbox Code Playgroud)


Yi *_*ang 13

在Python 3.5中,os.scandir如果需要检查文件属性或类型,则更好 - 请参阅os.DirEntry函数返回的对象的属性.

import os 

for file in os.scandir(path):
    if file.name.endswith(".bak"):
        os.unlink(file.path)
Run Code Online (Sandbox Code Playgroud)

这也不需要更改目录,因为每个目录DirEntry都已包含文件的完整路径.


gho*_*g74 8

你可以创建一个功能.为遍历子目录添加maxdepth.

def findNremove(path,pattern,maxdepth=1):
    cpath=path.count(os.sep)
    for r,d,f in os.walk(path):
        if r.count(os.sep) - cpath <maxdepth:
            for files in f:
                if files.endswith(pattern):
                    try:
                        print "Removing %s" % (os.path.join(r,files))
                        #os.remove(os.path.join(r,files))
                    except Exception,e:
                        print e
                    else:
                        print "%s removed" % (os.path.join(r,files))

path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")
Run Code Online (Sandbox Code Playgroud)