我想获取目录树中某处存在的任意文本文件(带有 .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 ) 来简化其余代码。
例如:
...
if fnmatch.fnmatch(file, '*.txt'):
print file
...
关于python - 从目录树中获取任意文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10304244/