Discuss / Python / 交作业——文件查询

交作业——文件查询

Topic source

安迪博德

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
# 编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

import os

def findFiles(key, input='.'):
    if os.path.isdir(input):
        for x in os.listdir(input):
            findFiles(key, os.path.join(input, x))
    else:
        doCheck(key, input)

def doCheck(key, fileName):
    # 尝试取得真正的文件名(不包括文件夹和文件扩展名)进行判断
    arr = os.path.split(fileName)
    if len(arr) > 1:
        realFileName = arr[1]
    else:
        realFileName = fileName
    if os.path.splitext(realFileName)[0].find(key) > -1:
        print(fileName)

if __name__ == "__main__":
    print("Please input the key to find:")
    key = input()
    findFiles(key)

  • 1

Reply