2012-04-24 29 views
2

我想要一個任意文本文件的路徑(使用.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 
+2

我可能會使用[splitext(http://docs.python.org/library/os.path.html#os.path.splitext)代替手動分割,但除此之外,它看起來很好。 – jterrace 2012-04-24 18:58:50

回答

2

我會使用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')) 
3

使用os.walk(就像你的例子)絕對是一個好的開始。

您可以使用fnmatchlink to the docs here)來簡化其餘的代碼。

E.g:

... 
    if fnmatch.fnmatch(file, '*.txt'): 
     print file 
...