Python recursively traverses folders and deletes objects,

Source: Internet
Author: User

Python recursively traverses folders and deletes objects,

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:16import osdef 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])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.