[英]How do I delete all folders within a folder except for one in python?
我正在Kodi中修改一個向導,我希望該向導刪除“附件”目錄中包含的所有文件夾,而不刪除我的向導。
該文件夾的目錄將使用Kodi內置的“ special://”功能。 我想刪除“ special:// home / addons”內部的所有內容,除了名為“ plugin.video.spartan0.12.0”的文件夾
我知道python需要使用“ xbmc.translatePath”函數來識別文件夾路徑,但是我不知道如何刪除文件夾中的所有內容而不刪除“ plugin.video.spartan0.12.0”
任何幫助,將不勝感激。
這是我目前擁有的
import os
dirPath = "C:\Users\Authorized User\AppData\Roaming\Kodi\addons"
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath+"/"+fileName)
這可能是多余的(有點草率),但對我有用:
import os
import shutil
#----------------------------------------------------------------------
def remove(path):
"""
Remove the file or directory
"""
if os.path.isdir(path):
try:
shutil.rmtree(path)
except OSError:
print "Unable to remove folder: %s" % path
else:
try:
if os.path.exists(path):
os.remove(path)
except OSError:
print "Unable to remove file: %s" % path
#----------------------------------------------------------------------
def cleanup(dirpath, folder_to_exclude):
for root, dirs, files in os.walk(dirpath, topdown=True):
for file_ in files:
full_path = os.path.join(root, file_)
if folder_to_exclude not in full_path:
print 'removing -> ' + full_path
remove(full_path)
for folder in dirs:
full_path = os.path.join(root, folder)
if folder_to_exclude not in full_path:
remove(full_path)
if __name__ == '__main__':
cleanup(r'c\path\to\addons', 'plugin.video.spartan0.12.0')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.