【发布时间】:2012-05-05 11:07:32
【问题描述】:
我想获取目录树中某处存在的任意文本文件(带有 .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
【问题讨论】:
-
我可能会使用splitext 而不是手动拆分,但除此之外,我觉得它看起来不错。
标签: python file operating-system directory performance