二、python在指定范围内查找目录和文件

在lib下创建pathdeal.py文件,内容如下:

import os
def getSpecialPath(dirName, topPathName = 'autotest'):
    '''根据目标目录名和给定顶层目录名,在此范围内返回目标目录'''
    '''目标目录名要唯一'''

    abPath = '' #目标目录路径,默认为空
    cp = '.' + os.path.sep #当前脚本的上层目录
    while len(dirName) > 1:
        p = os.path.abspath(cp) #当前脚本的绝对路径
        yid = os.walk(p)
        for rootDir, pathList, fileList in yid:
            for path in pathList:
                if dirName == path or dirName == path.lower():
                    abPath = os.path.join(rootDir, path)
                    return (abPath + os.path.sep)

        cp = cp + '..' + os.path.sep
        if topPathName == p[p.rfind(os.path.sep)+1:]:
            #msg = u"Not find special path: '%s', please confirm the path name is correct." % dirName
            #abPath = 'not found the dir'
            return False
def getSpecialFile(fileName, topPathName= 'autotest'):
    '''根据目标文件名和给定顶层目录名,在此范围内返回包含目标文件的绝对路径'''
    '''文件名要唯一'''
    if ':' in fileName:
        return fileName
    abPath = ''
    cp = '.' + os.path.sep
    while len(fileName) > 1:
        p = os.path.abspath(cp)
        yid = os.walk(p)
        for rootDir, pathList, fileList in yid:
            for file in fileList:
                if os.path.sep in fileName:
                    fp = os.path.join(rootDir, file)
                    if fileName in fp or fileName in fp.lower():
                        abPath = os.path.join(rootDir, fp)
                        return (abPath)
                else:
                    if fileName == file or fileName == file.lower():
                        abPath = os.path.join(rootDir, file)
                        return (abPath)

        cp = cp + '..' + os.path.sep
        if topPathName == p[p.rfind(os.path.sep) + 1:]:
            #msg = "Not find special file: '%s', please confirm the file name is correct." % fileName
            #logging.debug(msg)
            abPath = 'not found the file'
            return abPath
if __name__ == '__main__':
    tp = getSpecialPath('logs')
    print('返回的目录路径:\n', tp)

    tf = getSpecialFile('alidata.xml')
    print('返回的文件路径:\n', tf)

运行结果如下:

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值