我想得到一个任意文本文件的路径(后缀为.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
使用
os.walk
(就像在您的例子中一样)绝对是一个好的开始。在您可以使用
fnmatch
(link to the docs here)来简化其余的代码。在例如:
我将使用fnmatch而不是字符串操作。在
我还重写了函数,使其更通用(和“pythonic”)。要只获得一个路径名,请这样称呼它:
^{pr2}$相关问题 更多 >
编程相关推荐