Python 检索目录下所有文件中包含指定字符串的文件

本文介绍了一个Python脚本,该脚本可以遍历指定目录及其子目录下的所有文件,并找出包含特定字符串的文件。通过正则表达式匹配,能够高效地定位到含有目标字符串的文件,对于代码审查或文件搜索非常实用。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

http://blog.youkuaiyun.com/authorzhh/article/details/8933758

#!/usr/bin/env python
# 1.py
# use UTF-8
# Python 3.3.0

# 检索目录下所有文件中包含指定字符串的文件
import os
import re

# 枚举dirPath目录下的所有文件
def ListFiles(dirPath):
#begin
	fileList = []
	for root, dirs, files in os.walk(dirPath):			# 注意os.walk的功能
	#begin
		for fileObj in files:
		#begin
			fileList.append(os.path.join(root, fileObj))
		#end
	#end
	return fileList
#end

def FindString(filePath, regex):
#begin
	fileObj = open(filePath, 'r')
	for eachLine in fileObj:
	#begin
		if re.search(regex, eachLine, re.I):
		#begin
			print(fileObj)		#打印文件对象
			break
		#end
	#end
#end


def main():
#begin
	fileDir = "F:" + os.sep + "aaa"		# 查找F:\aaa 目录下
	regex = 'include'					# 包含include 的文件
	fileList = ListFiles(fileDir)
	print(fileList)
	for fileObj in fileList:
	#begin
		FindString(fileObj, regex)
	#end
	os.system("pause")
#end

if __name__ == '__main__':
#begin
	main()
#end

# 输出:
# <_io.TextIOWrapper name='F:\\aaa\\1.cpp' mode='r' encoding='cp936'>
# <_io.TextIOWrapper name='F:\\aaa\\2.h' mode='r' encoding='cp936'>
# <_io.TextIOWrapper name='F:\\aaa\\3.c' mode='r' encoding='cp936'>
# <_io.TextIOWrapper name='F:\\aaa\\4.h' mode='r' encoding='cp936'>
# <_io.TextIOWrapper name='F:\\aaa\\5.cpp' mode='r' encoding='cp936'>
# <_io.TextIOWrapper name='F:\\aaa\\6.h' mode='r' encoding='cp936'>
# <_io.TextIOWrapper name='F:\\aaa\\我.cpp' mode='r' encoding='cp936'>

# 遇到的问题有
# 如果做枚举到的文件不是文本文件, 例如rar文件, 就会有异常产生


您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值