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

来源:互联网 发布:孤岛危机3优化怎么样 编辑:程序博客网 时间:2024/06/04 20:03
功能:查找包含关键字的文件。
注:输入若干个参数,其中,最后一个参数为要查找的目录,默认为当前目录。其余为所要查找的关键字列表。程序稍作修改即可查询所有文件。python不能递归太多,想办法对递归做优化。
当要进行深度递归时,出现错误,如:递归opendaylight文件夹。以后学习os.walk()和os.path.walk()。

#! usr/bin/env python# -*- coding:utf-8 -*-import osimport sysclass Search_file(object):def __init__(self, args = os.path.abspath('.')):self.args = argsdef search_file(self, all_file , dir_path, sub_dir):#print sub_dirfor 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_dir1except WindowsError, e:print 'no authority for this file',sub_dir1def 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_dirself.search_dir_file(file, path, sub_dir)except WindowsError, e:print 'no authority for this folder:',pathreturn args = sys.argvargs.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
原创粉丝点击