Python 从目录树中获取任意文件
我想获取目录树中某个地方的任意文本文件(后缀为.txt)的路径。文件不应隐藏或位于隐藏目录中 我试着写代码,但看起来有点麻烦。您将如何改进它以避免无用的步骤Python 从目录树中获取任意文件,python,file,operating-system,directory,performance,Python,File,Operating System,Directory,Performance,我想获取目录树中某个地方的任意文本文件(后缀为.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 = o
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
()简化其余代码
例如:
我会用它来代替字符串操作
import os, os.path, fnmatch
def find_files(root, pattern, exclude_hidden=True):
""" Get the path to arbitrary .ext file under the root dir """
for dir, _, files in os.walk(root):
for f in fnmatch.filter(files, pattern):
path = os.path.join(dir, f)
if '/.' not in path or not exclude_hidden:
yield path
我还将函数重写为更通用的(和“pythonic”)。要仅获取一个路径名,请按如下方式调用它:
first_txt = next(find_files(some_dir, '*.txt'))
我可能会使用,而不是手动拆分,但除此之外,它看起来不错。
first_txt = next(find_files(some_dir, '*.txt'))