[英]Deleting all files in a directory with Python
我想刪除目錄中所有擴展名為.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.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)
在 Python 3.5 中,如果您需要檢查文件屬性或類型,則os.scandir
會更好 - 請參閱os.DirEntry
了解函數返回的對象的屬性。
import os
for file in os.scandir(path):
if file.name.endswith(".bak"):
os.unlink(file.path)
這也不需要更改目錄,因為每個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")
我意識到這是舊的; 但是,這將是如何僅使用 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))
在 Linux 和 macOS 上,您可以對 shell 運行簡單的命令:
subprocess.run('rm /tmp/*.bak', shell=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.