Fuzzy Lookup
| The code is as follows |
Copy Code |
| Import OS From Glob import Glob #用到了这个模块 def search_file (pattern, search_path=os.environ[' path '], PATHSEP=OS.PATHSEP): For path in Search_path.split (OS.PATHSEP): For match in Glob (path, pattern): Os.path.join Yield match if __name__ = = ' __main__ ': Import Sys If Len (sys.argv) <2 or Sys.argv[1].startswith ('-'): #sys. argv[0] is the current path, and 1 starts with the following arguments 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 |
Specify file name for exact lookup
| The code is as follows |
Copy Code |
| Import Os,optparse #1: Exact Search def search_file (filename, search_path=os.environ[' path '), PATHSEP=OS.PATHSEP): #os. Pathsep is a separator '; ' For path in Search_path.split (OS.PATHSEP): candidate = os.path.join (path, filename) #预选路径 If Os.path.isfile (candidate): Yield Os.path.abspath (candidate) #用生成器可以方便控制返回的数据. You can use the. Next () method to return only the next subkey Def Parse_args (): #帮助提示 Usage = U ' "This is a script to find out if a file is specified in the folder path. The first parameter is the file name to look for, and the second is the path ' Parser = Optparse. Optionparser (usage) Help = U ' name of file to find ' Parser.add_option ('--filename ', help=help) #type = ' int ', Help = U ' Find path multiple paths with; 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: Find A. php file that starts with a to D in the e:/py and e:/phpwww directories
E:py>python_cook [a-d]*.php e:/py;e:/phpwww
2 match
e:/phpwwwcurl.php
e:/phpwwwduoxiancheng.php