美文网首页
Python3 搜索文件名称

Python3 搜索文件名称

作者: fd320d65dbd8 | 来源:发表于2017-07-26 17:23 被阅读16次

Python3 学习

  • 编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出绝对路径。
import os
import sys

def searchFi(path,key):
    result = []
    for x in os.listdir(path):
        filePath = os.path.join(os.path.abspath(path),x)
        if os.path.isfile(filePath) and key in os.path.splitext(filePath)[0]:
            result.append(filePath)
        elif os.path.isdir(x):
            result.extend(searchFi(x,key))
    return result

if __name__ == '__main__':
    argv = sys.argv

    if len(argv) > 2:
        path = argv[1]
        key = argv[2]
    else:
        path = '.'
        key = 'test'

    re = searchFi(path,key)
    print('搜索关键字为:%s , 目标文件夹:%s' % (key,path))
    if len(re)==0:
        print('搜索结果为空,请尝试修改关键字')
    for i,v in enumerate(re):
        print('第%s个结果,为:%s' % (i+1,v))

使用方法和结果如下:

# jonhory @ Jonhory-MBP in ~/Desktop/PY on git:master x [17:18:09] C:126
$ python3 /Users/jonhory/Desktop/PY/OSPractice.py /Users/jonhory/Desktop/LinuxShell linu
搜索关键字为:linu , 目标文件夹:/Users/jonhory/Desktop/LinuxShell
第1个结果,为:/Users/jonhory/Desktop/LinuxShell/Linux公社www.linuxidc.com.url

相关文章

网友评论

      本文标题:Python3 搜索文件名称

      本文链接:https://www.haomeiwen.com/subject/tnsokxtx.html