我想在一个目录中删除所有扩展名为
.bak
的文件。我该如何使用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))
仅使用单个循环:
for f in os.listdir(mydir):
if not f.endswith(".bak"):
continue
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
函数进行切换。
os.scandir
会更好 - 请查看os.DirEntry
以获取返回的对象的属性。import os
for file in os.scandir(path):
if file.name.endswith(".bak"):
os.unlink(file.path)
由于每个DirEntry
已经包含文件的完整路径,因此这也不需要更改目录。
if file.name.endswith(".bak"):
。 - TSeymour使用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)
您可以创建一个函数。添加最大深度以遍历子目录。
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")
我知道这篇文章有点旧了,但是下面是如何仅使用os模块来实现...
def purgedir(parent):
for root, dirs, files in os.walk(parent):
for item in files:
# Delete subordinate files
filespec = os.path.join(root, item)
if filespec.endswith('.bak'):
os.unlink(filespec)
for item in dirs:
# Recursively perform this operation for subordinate directories
purgedir(os.path.join(root, item))
对于一行解决方案(适用于Windows
和Linux
);
import glob,os
for file in glob.glob("<your_path>/*.bak"): print(file," these will be deleted")
if input("continue ?") == "Y":
for file in glob.glob("<your_path>/*.bak"): os.remove(file)
from pathlib import Path
for file in Path("/path/to/folder").glob("*"):
file.unlink()
for file in Path("/path/to/folder").rglob("*.txt"):
file.unlink()
在Linux和macOS上,您可以在shell中运行简单的命令:
subprocess.run('rm /tmp/*.bak', shell=True)
shutil.rmtree(path)
。 - jfs