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)

相关推荐