mik*_*iku 251
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.
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都已包含文件的完整路径.
你可以创建一个功能.为遍历子目录添加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)