Python implementation example of retaining specific folders and files when deleted

不言
Release: 2018-04-27 10:56:31
Original
2104 people have browsed it

下面为大家分享一篇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)
Copy after login


相关推荐:

python 删除非空文件夹的实例



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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!