我有这个代码,我搜索一个值(inputCategory),它通常位于路径的末尾(例如/blah/blah/<category/blah
或有时/blah/blah/<category>
def category_search(inputDirectory, inputCategory, root):
categorySearch = os.path.split(os.path.normpath(inputDirectory))
if categorySearch[1] == inputName:
Logger.info("SEARCH: Files appear to be in their own directory")
categorySearch2 = os.path.split(os.path.normpath(categorySearch[0]))
if categorySearch2[1] == twoCategory or categorySearch2[1] == oneCategory:
if not inputCategory:
Logger.info("SEARCH: Determined Category to be: %s", categorySearch2[1])
inputCategory = categorySearch2[1]
elif not inputCategory:
Logger.error("SEARCH: Could not identify category from the directory structure.")
sys.exit(-1)
else:
pass
elif categorySearch[1] == twoCategory or categorySearch[1] == oneCategory:
if os.path.isdir(os.path.join(inputDirectory, inputName)):
inputDirectory = os.path.join(inputDirectory, inputName)
else:
Logger.info("SEARCH: The directory passed is the root directory for category %s", categorySearch[1])
Logger.info("SEARCH: We will try and determine which files to process, individually")
root = 1
if not inputCategory:
Logger.info("SEARCH: Determined Category to be: %s", categorySearch[1])
inputCategory = categorySearch[1]
elif not inputCategory:
Logger.error("SEARCH: Could not identify category from the directory structure")
sys.exit(-1)
else:
Logger.info("SEARCH: The directory passed does not appear to include a category")
root = 1
return inputDirectory, inputCategory, root
但问题是代码不是很动态,例如,如果我得到像/blah/blah/<category>/blah/blah
我正在寻找有关如何优化此代码的输入,捕获上述情况以及可能更多的情况?
我在python上很新,所以要温柔:)感谢您的帮助!
答案 0 :(得分:0)
我使用这样的东西进行路径检查,但不确定它是否适合你... 我也是非常绿色的蟒蛇!
# deconstruct the folder: /a/b/c --> /a/b --> /a --> /
pathHead, pathTail = os.path.split(inputDirectory)
while pathTail and ( pathTail != inputCategory ):
pathHead,pathTail = os.path.split(pathHead)
if not pathTail:
print 'didnt find category'
else:
print 'found category: ',pathTail , ' in path: ' , pathHead
编辑:修复elif到其他地方......