1

特定のフォルダー内のすべてのファイル (およびオプションでフォルダー、オプションでサブディレクトリを再帰的に) を列挙する通常の方法はありますか? そのため、フォルダー パスを渡し、結果のフル パスのリストを取得します。

この結果からすべての読み取り専用ファイルとすべての隠しファイルを除外する方法を示すと、より良い結果が得られます。入力パラメータ:

  • dir: フォルダーのフルパス
  • option_dirs: リストへのディレクトリ パスを含めます
  • option_subdirs: dir のすべてのサブディレクトリも処理します
  • option_no_ro: 読み取り専用ファイルを除外します
  • option_no_hid: 隠しファイルを除外

Python2.

4

1 に答える 1

5

おそらく と を調べる必要がos.walkありos.accessます。

実際の実装では、次のようなことができます。

import os

def get_files(path, option_dirs, option_subdirs, option_no_ro, option_no_hid):
    outfiles = []
    for root, dirs, files in os.walk(path):
        if option_no_hid:
            # In linux, hidden files start with .
            files = [ f for f in files if not f.startswith('.') ]
        if option_no_ro:
            # Use os.path.access to check if the file is readable
            # We have to use os.path.join(root, f) to get the full path
            files = [ f for f in files if os.access(os.path.join(root, f), os.R_OK) ]
        if option_dirs:
            # Use os.path.join again
            outfiles.extend([ os.path.join(root, f) for f in files ])
        else:
            outfiles.extend(files)
        if not option_subdirs:
            # If we don't want to get subdirs, then we just exit the first
            # time through the for loop
            return outfiles
    return outfiles
于 2013-07-22T21:43:32.520 に答える