我想获取目录树中某处存在的任意文本文件(带有.txt后缀)的路径。该文件不应隐藏或在隐藏目录中。
我试图编写代码,但它看起来有点麻烦。您将如何改进它以避免无用的步骤?
def getSomeTextFile(rootDir):
"""Get the path to arbitrary text file under the rootDir"""
for root, dirs, files in os.walk(rootDir):
for f in files:
path = os.path.join(root, f)
ext = path.split(".")[-1]
if ext.lower() == "txt":
# it shouldn't be hidden or in hidden directory
if not "/." in path:
return path
return "" # there isn't any text file