


思路:
遍历文件夹下面的文件夹
如果文件夹名称等于".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中文网!

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools