Home  >  Article  >  Backend Development  >  Python implements recursive traversal of folders and deletion of files

Python implements recursive traversal of folders and deletion of files

高洛峰
高洛峰Original
2017-01-14 15:18:361645browse

思路:

遍历文件夹下面的文件夹
如果文件夹名称等于".svn",则修改文件夹的属性(因为".svn"的文件都是只读的,你不能直接删除)
删除此文件夹
如果文件夹名称不等于".svn",则递归上面的方法

Python的实现

代码

import os
import shutil
import os.path
import stat
rootdir="F:\\work\\Test"
for parent,dirnames,filenames in os.walk(rootdir): #遍历文件夹下面的所有文件夹 
  
  for dirname in dirnames:   
    if dirname=='.svn':
      strfilepath=parent+os.sep+dirname
      if os.path.isdir(strfilepath):
        os.system('attrib -r ' + parent + '\\*.* /s')#设置本文件夹可写
        os.system('attrib -r ' + strfilepath + '\\*.* /s')#设置父文件夹可写        
        shutil.rmtree(parent+os.sep+dirname)#删除此文件夹

要点:

Walk在os模块下面,用来根据提供的文件夹生成一个generator。每次可以得到一个三元tupple,其中第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
os.system('attrib -r ' + parent + '\\*.* /s') 设置文件夹可写
shutil.rmtree(parent+os.sep+dirname) 删除文件夹(即使文件夹里面有文件)

例二:

Python实现递归遍历指定文件目录(startdir),从而找到所有与指定的文件或目录(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)

关于该程序的一点说明:

1. 函数scandir的形参target可以是目录名也可以是文件名。
2. 函数chdir的作用是切换到指定目录,该参数必须是有效的且有访问权限的相对路径或绝对路径。
3. 函数的第五行,使用getcwd函数也是为了取得当前绝对路径。
4. 加号作为字符串的连接符。os.sep根据你的操作系统给出目录分隔符,在GNU/Linux和UNIX上它的返回值是'/',在windows上它的返回值是'\\',在Mac OS上是‘:',使用os.sep而不直接使用字符,会提高程序的可移植性。
5. 递归调用后,一定不能忘了os.chdir(os.pardir),返回上层目录(即父目录)。

重要:

1. 理解for中的两个并列的if语句,并列是为了解决目标是文件夹时,该目标文件夹中包含符合要求的文件夹。
2. 如果指定目录中存在访问受限的文件或文件夹,该程序会失败,返回无权访问信息。

例三:

Python递归遍历文件夹,寻找包含某个字符串的文本文件

linux下,如果不使用eclipse的话,想查找某个字符串在哪些文件中出现过就很麻烦,自己写了这个脚本在编码时使用,挺方便的。如果某个文本文件中包含的话,则只记录出现第一次的行数输出
使用方法:
python xxx.py 路径 字符串

python search_content.py /home/www/ abcdefg

search_content.py

#!/use/bin/env python
#-*- coding:utf-8 -*-
import sys,os
filterType = ['gif','png','bmp','jpg','jpeg','rar','zip',
      'ico','apk','ipa','doc','docx','xls','jar',
      'xlsx','ppt','pptx','pdf','gz','pyc','class']
num = 0
def 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('.'): #不检查隐藏文件夹
    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  %s" % (path,index+1))
      break
  return
if __name__ == "__main__":
  if len(sys.argv) < 3:
    print("invalid parameters")
  else:
    search(sys.argv[1],sys.argv[2])

更多Python实现递归遍历文件夹并删除文件相关文章请关注PHP中文网!

Statement:
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