『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")

你可能感兴趣的:(Python学习,工作)