This article summarizes three Python code for traversing folders and deleting them, mainly to share with you the implementation ideas of these three methods. if you need them, you can refer to the following ideas:
Traverse folders under a folder
If the folder name is ". svn", modify the folder attributes (because the files in ". svn" are read-only and cannot be deleted directly)
Delete this folder
If the folder name is not equal to ". svn", recursive the above method
Python implementation
Code
Import osimport shutilimport OS. pathimport statrootdir = "F: \ work \ Test" for parent, dirnames, filenames in OS. walk (rootdir): # traverse all folders under the folder for dirname in dirnames: if dirname = '. svn ': strfilepath = parent + OS. sep + dirname if OS. path. isdir (strfilepath): OS. system ('B B-R' + parent + '\\*. */s ') # set this folder to writable OS. system ('B B-R' + strfilepath + '\\*. */s ') # set the parent folder to write shutil. rmtree (parent + OS. sep + dirname) # Delete this folder
Key points:
Under the OS module, the Walk is used to generate a generator based on the provided folder. You can get a three-element tupple each time. The first is the Start Path, the second is the folder in the Start Path, and the third is the file in the Start Path.
OS. system ('B B-R' + parent +' \ *. */s ')
Shutil. rmtree (parent + OS. sep + dirname) delete a folder (even if there are files in the folder)
Example 2:
Python recursively traverses the specified file directory (startdir) to find the absolute path of all files or directories with the same name as the specified file or directory (target.
Scandir. py:
#! /usr/bin/python# filename : scandir.py# author : Jesse# update : 2011/08/15 10:16 import os def scandir(startdir, target) : os.chdir(startdir) for obj in os.listdir(os.curdir) : if obj == target : print os.getcwd() + os.sep + obj if os.path.isdir(obj) : scandir(obj, target) os.chdir(os.pardir) #!!! startdir = raw_input('Please input startdir: ')target = raw_input('Please input target: ')scandir(startdir, target)
A description of the program:
1. the target parameter of the scandir function can be either a directory name or a file name.
2. the Function chdir is used to switch to the specified directory. this parameter must be a valid and accessible relative or absolute path.
3. the fifth line of the function uses the getcwd function to obtain the current absolute path.
4. the plus sign is used as the connector of the string. OS. sep provides a directory separator based on your operating system. on GNU/Linux and UNIX, the return value is '/', and on windows, the return value is '\\', on Mac OS, it is ':' and OS is used. sep without directly using characters, it will improve the portability of the program.
5. After recursive calling, you must not forget OS. chdir (OS. pardir) and return to the upper Directory (parent directory ).
Important:
1. understand the two parallel if statements in for. when the target is a folder, the target folder contains a folder that meets the requirements.
2. if a restricted file or folder exists in the specified directory, the program will fail and no access information is returned.
Example 3:
Python recursively traverses folders to find text files containing a string
In linux, if you do not use eclipse, it is very difficult to find out which files have been used by a string. it is very convenient to write this script for encoding. If a text file contains data, only the first row output is recorded.
Usage:
Python xxx. py path string
Python search_content.py/home/www/abcdefg
Search_content.py
#! /Use/bin/env python #-*-coding: UTF-8-*-import sys, osfilterType = ['GIF', 'PNG ', 'bmp', 'jpg ', 'jpeg ', 'rar', 'Zip ', 'ico', 'apk ', 'ipa', 'Doc', 'docx', 'XLS ', 'jar ', 'xlsx', 'ppt ', 'ppt', 'PDF', 'gz ', 'pyc', 'class'] num = 0def search (path = None, cont = None): if not path or not cont: print ('path or searchString is empty ') return global num _ loopFolder (path, cont) print ("% s file find" % num) def _ loopFolder (path, cont): arr = path. split ('/') if not arr [-1]. startswith ('. '): # Do not check the hidden folder if OS. path. isdir (path): folderList = OS. listdir (path) for x in folderList: _ loopFolder (path + "/" + x, cont) elif OS. path. isfile (path): _ verifyContent (path, cont) def _ verifyContent (path, cont): if path. split ('. ') [-1]. lower () in filterType: return global num fh = open (path, 'r') fhContent = fh. readlines () fh. close () for index, x in enumerate (fhContent): if cont in x: num + = 1 print ("% s" % (path, index + 1 )) break returnif _ name _ = "_ main _": if len (sys. argv) <3: print ("invalid parameters") else: search (sys. argv [1], sys. argv [2])
For more articles about how to recursively traverse folders and delete files in Python, refer to PHP!