『Pythonワーク』ファイル検索器


#! /usr/bin/ env python
# coding:utf-8

"""
__author__ = "LCG22"
__create_date__ = "2016-10-12"
"""

import os
import logging
import time

global file_list
file_list = []

ISOTIMEFORMAT = "%Y-%m-%d %X"

def mylog(msg):
    """
                
    :param msg:
    :return:
    """

    logging.basicConfig(
        level=logging.DEBUG,
        format='[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename=r'find_file.log',
        filemode='a'
    )
    logging.debug("datetime: %s, msg: %s" % (time.strftime(ISOTIMEFORMAT, time.localtime()), msg))

    return None


def find_main(file_path, word="", file_format=""):
    """
                             ,                              ,     
    :param file_path: str    ,       
    :param word:         
    :param file_format:        
    :return:
    """

    #         
    assert word is not "" and file_format is not "", "          "

    #        
    try:
        assert isinstance(word, str), "           "
        assert isinstance(file_format, str), "           "
    except Exception, e:
        print e

    try:
        global file_list
        all_file_name = os.listdir(file_path)
        for file_name in all_file_name:
            sub_file_path = file_path + "\\%s" % file_name
            if os.path.isdir(sub_file_path):
                os.chdir(sub_file_path)
                find_main(sub_file_path, word, file_format)
            else:
                #           
                if word is not "" and file_format is not "":
                    if word in sub_file_path.split("\\")[-1].split(".")[0] and \
                                    sub_file_path.split("\\")[-1].split(".")[-1] == file_format:
                        file_list.append(sub_file_path)

                if word is not "" and file_format is "":
                    if word in sub_file_path.split("\\")[-1].split(".")[0]:
                        file_list.append(sub_file_path)

                if word is"" and file_format is not "":
                    if sub_file_path.split("\\")[-1].split(".")[1] == file_format:
                        file_list.append(sub_file_path)
    except WindowsError, we:
        mylog(we)

    print file_list

    return file_list

if __name__ == '__main__':
    find_main(r"c:/", "1", "xls")