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
4

2 に答える 2

3

os.walk(あなたの例のように)使用することは間違いなく良いスタートです。

fnmatchここのドキュメントへのリンク)を使用して、残りのコードを簡略化できます。

例えば:

...
    if fnmatch.fnmatch(file, '*.txt'):
        print file
...
于 2012-04-24T19:50:03.113 に答える
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」)ように書き直しました。パス名を1つだけ取得するには、次のように呼び出します。

 first_txt = next(find_files(some_dir, '*.txt'))
于 2012-04-24T19:53:05.740 に答える