下面为大家分享一篇Python实现删除时保留特定文件夹和文件的示例,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧
实现功能:删除当前目录下,除保留目录和文件外的所有文件和目录
#!bin/env python import os import os.path import shutil def DeleteFiles(path, remainDirsList, filesList): dirsList = [] dirsList = os.listdir(path) for f in dirsList: if f not in remainDirsList: filePath = os.path.join(path,f) if os.path.isdir(filepath): shutil.rmtree(filepath, True) if f in filesList: filepath = os.path.join(path,f) os.remove(f) if __name__ == "__main__": path=os.getcwd()+"\\" #当前目录中需要保留的文件 filesList=['a.txt','b.txt'] #当前目录中需要保留的文件夹 dirsList=['test'] DeleteFiles(path,fileList,dirsList)
相关推荐:
The above is the detailed content of Python implementation example of retaining specific folders and files when deleted. For more information, please follow other related articles on the PHP Chinese website!