玩蛇网提供最新Python编程技术信息以及Python资源下载!

linux下搜索文件的python方法

python 培训

linux下如何用python方法来搜索文件,看看我写的方法是否可行。新手练习,多多指教!

python fsearch.py <file_pattern> [-p] 'path1 path2 path3'

os、sys、glob、re是代码中需要用到的几个方法

如果加-p选项则为指定目录查找
如果在-p选项添加完后跟一个-d选项则为深度查找

#!/usr/bin/env python
import os, sys, glob, re

if sys.hexversion < 0x02040000:
        print >> sys.stderr, 'Your python version is too old (%s)' % \
                                                        (sys.version.split()[0])
        print >> sys.stderr, 'You need at least Python 2.4'
        sys.exit(1)

PPATH = False

def search_all_files(pattern, search_path, pathsep=os.pathsep):
    for path in search_path.split(pathsep):
        '''
        candidate = os.path.join(path, filename)
        if os.path.isfile(candidate):
            return os.path.abspath(candidate)
        '''
        for match in glob.glob(os.path.join(path, pattern)):
            yield match

def print_file(pattern, path=None):
    if PPATH:
	p = path.split(' ')
	path = lambda p : os.pathsep.join(p)
	matches = list(search_all_files(pattern, path(p)))
	if matches:
            for match in matches:
                print match
        else:
		print "Not find like '%s' !" % pattern
		sys.exit(1)
    else:
       	matches = list(search_all_files(pattern, os.environ['PATH']))
	if matches:
	    for match in matches:
		print match
	else:
	    print "Not find like '%s' !" % pattern
	    sys.exit(1)

def deep_search(fpattern, path):
	pathlist = path.split(' ')
	finded = False
	for p in pathlist:
		if os.path.exists(p):
			for dirpath, dirnames, filenames in os.walk(p):
				for file in filenames:
					fullpath = os.path.join(dirpath, file)
					if re.search(fpattern, fullpath):
						print fullpath
						finded = True
					else:
						continue
		else:
			print "[*]Path %s don't exit !" % p
			sys.exit(1)
	if not finded:
		print "Don't find like %s !" % fpattern

if __name__ == '__main__':
    if '-p' in sys.argv:
	PPATH = True
	if '-d' not in sys.argv:
		if len(sys.argv) != 4 or sys.argv[1].startswith('-'):
	    		print "Usage %s <pattern> -p 'path1 path2 path3....' use escape to split pathname" % sys.argv[0]
		else:
	    		print_file(sys.argv[1], sys.argv[3])
	elif sys.argv[4] == '-d':
		deep_search(sys.argv[1], sys.argv[3])
    else:
	if len(sys.argv) != 2 or sys.argv[1].startswith('-'):
		print "Usage %s <pattern> " % sys.argv[0]
		sys.exit(1)
        else:
            print_file(sys.argv[1])

Python文件操作相关文章推荐:
1、Python遍历文件夹目录与文件操作
2、Python 文件对象常用内建方法

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/base/b2138.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-06-24 10:09 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部