Python implements a method to find a specified file in a directory
- 2020-04-02 14:22:28
- OfStack
This article illustrates how a python implementation can find a specified file in a directory. Share with you for your reference. The specific implementation method is as follows:
1. Fuzzy search
import os
from glob import glob # This module is used
def search_file(pattern, search_path=os.environ['PATH'], pathsep=os.pathsep):
for path in search_path.split(os.pathsep):
for match in glob(os.path.join(path, pattern)):
yield match
if __name__ == '__main__':
import sys
if len(sys.argv)<2 or sys.argv[1].startswith('-'):#sys.argv[0] Is the current path ,1 It starts with the following argument
print 'Use: %s <pattern>' % sys.argv[0]
sys.exit(1)
if len(sys.argv)>2:
matchs = list(search_file(sys.argv[1],sys.argv[2]))
else:
matchs = list(search_file(sys.argv[1]))
print '%d match' % len(matchs)
for match in matchs:
print match
2. Find the specified file name exactly
import os,optparse
#1: Accurate search
def search_file(filename, search_path=os.environ['PATH'], pathsep=os.pathsep):#os.pathsep The separator is ';'
for path in search_path.split(os.pathsep):
candidate = os.path.join(path, filename)# Primary path
if os.path.isfile(candidate):
yield os.path.abspath(candidate) # The generator makes it easy to control the returned data . You can use .next() Method returns only the next subitem
def parse_args():# Helpful tips
usage = u''' This is a script that looks for files in the folder path ,
The first parameter is the filename to look for, and the second is the path '''
parser = optparse.OptionParser(usage)
help = u' The name of the file to look for '
parser.add_option('--filename', help=help)#type='int',
help = u' Find multiple paths to ; separated '
parser.add_option('--path', help=help, default='e:')
options, args = parser.parse_args()
return options, args
if __name__ == '__main__':
options, args = parse_args()
find_file = list(search_file(args[0], args[1]))
if find_file:
for file in find_file:
print "Found File at %s" % file
else:
print "Not Found"
Example: look for.php files starting with a through d in the e: / py and e: / PHPWWW directories
E: p y > Python_cook [a - d] *. PHP: e/p y; E: / PHPWWW
2 match
E: / phpwwwcurl. PHP
E: / phpwwwduoxiancheng. PHP
I hope this article has helped you with your Python programming.