Home > other >  Python implementation deleted keep specific folders and files? Error code?
Python implementation deleted keep specific folders and files? Error code?

Time:02-04

Realize functions: delete the current directory, directory and file are retained all files and directories

 #! Bin/env python 
The import OS
The import OS. Path
The import shutil

Def DeleteFiles (path, remainDirsList filesList) :
DirsList=[]
DirsList=OS. Listdir (path)
For f in dirsList:
If f is 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 () + "\ "
# the need to keep files in the current directory
FilesList=[' a.t xt ', 'b.t xt]
# of the need to keep in the current directory folder
DirsList=[' test ']
DeleteFiles (path, fileList, dirsList)

CodePudding user response:

Did you pass parameters when make order inside out, check the DeleteFiles the function parameter order,
Think we should first determine f is a directory or file, and then to determine whether need to keep part of the next reoccupy corresponding file delete or remove methods to deal with,
And this a
If f in filesList:
.
Do you want the file deletion in the fileslist?
  • Related