指定したディレクトリにあるファイル名を取得する方法

ディレクトリ /home/user/DIR にファイル file1, file2, file3 が格納されているとします。DIR ディレクトリに含まれるファイルの名前とフルパスを取得する方法です。

  • dirpath … 文字列、ディレクトリへのパス
  • dirnames … dirpath 内のサブディレクトリ名のリスト ('.' と '..' は除く)
  • filename … dirpath 内の非ディレクトリ・ファイル名のリスト
import os

for dirpath, dirnames, filenames in os.walk("ディレクトリ名"):
   for name in filenames:
      print name, os.path.join(dirpath, name)

出力結果は以下のようになります。

file1 /home/user/DIR/file1
file2 /home/user/DIR/file2
file3 /home/user/DIR/file3


こちらのURLを参照させていただきました。
http://www.python.jp/doc/release/lib/os-file-dir.html