在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)
运行结果如下: