我想要一個任意文本文件的路徑(使用.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(http://docs.python.org/library/os.path.html#os.path.splitext)代替手動分割,但除此之外,它看起來很好。 – jterrace 2012-04-24 18:58:50