自己写的第一个python目录及文件查找下程序

功能:查找包含关键字的文件。
注:输入若干个参数,其中,最后一个参数为要查找的目录,默认为当前目录。其余为所要查找的关键字列表。程序稍作修改即可查询所有文件。python不能递归太多,想办法对递归做优化。
当要进行深度递归时,出现错误,如:递归opendaylight文件夹。以后学习os.walk()和os.path.walk()。

#! usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys

class Search_file(object):
	def __init__(self, args = os.path.abspath('.')):
		self.args = args
		
	def search_file(self, all_file , dir_path, sub_dir):
		#print sub_dir
		for file in all_file:
			for x in os.listdir(dir_path):
				try:
					path = os.path.join(dir_path, x)
					if os.path.isfile(path):
						if 0<=x.find(file):
							sub_dir1 = os.path.join(sub_dir, x)
							print sub_dir1
				except WindowsError, e:
					print 'no authority for this file',sub_dir1
					
	def search_dir_file(self, file, dir_path = os.path.abspath('.'), sub_dir = ''):
		self.search_file(file, dir_path, sub_dir)
		for x in os.listdir(dir_path):
			try:
				path = os.path.join(dir_path, x)
				if os.path.isdir(path):
					sub_dir = os.path.join(sub_dir, x)
					#print 'diretory:',sub_dir
					self.search_dir_file(file, path, sub_dir)
			except WindowsError, e:
				print 'no authority for this folder:',path
		return 		
		
args = sys.argv
args.pop(0)
if len(args)==0:
	print 'hello, you must enter a file name which you want to search!'
elif len(args)>=2:	
	if os.path.isdir(args[-1]):
		dire = args.pop(-1)
		files = Search_file()
		files.search_dir_file(args, dire)
	else:
		files = Search_file()
		files.search_dir_file(args)






	



2014/9/4  19:51 针对系统的文件夹及文件的权限访问异常问题,加入了异常机制。
最后附上针对尾递归优化的文章: http://www.csharpwin.com/csharpspace/12293r3050.shtml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值