Python でのディレクトリ ツリーのリスト
-
02-07-2019 - |
質問
Python で指定されたディレクトリ内のすべてのファイル (およびディレクトリ) のリストを取得するにはどうすればよいですか?
解決
これは、ディレクトリ ツリー内のすべてのファイルとディレクトリを横断する方法です。
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
他のヒント
使用できます
os.listdir(path)
参考およびその他の OS 機能については、ここを参照してください。
- Python 2 ドキュメント: https://docs.python.org/2/library/os.html#os.listdir
- Python 3 ドキュメント: https://docs.python.org/3/library/os.html#os.listdir
私がよく使うヘルパー関数は次のとおりです。
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
import os
for filename in os.listdir("C:\\temp"):
print filename
グロビング機能が必要な場合は、そのためのモジュールもあります。例えば:
import glob
glob.glob('./[0-9].*')
次のようなものを返します:
['./1.gif', './2.txt']
ドキュメントを参照してください ここ.
これを試して:
import os
for top, dirs, files in os.walk('./'):
for nm in files:
print os.path.join(top, nm)
パスを指定しない現在の作業ディレクトリ内のファイルの場合
Python 2.7:
import os
os.listdir(os.getcwd())
Python 3.x:
import os
os.listdir()
Python 3.x に関するコメントをくださった Stam Kaly に感謝します。
再帰的な実装
import os
def scan_dir(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path):
print path
else:
scan_dir(path)
必要なオプションをすべて含めた長いバージョンを書きました。 http://sam.nipl.net/code/python/find.py
ここにも当てはまると思います:
#!/usr/bin/env python
import os
import sys
def ls(dir, hidden=False, relative=True):
nodes = []
for nm in os.listdir(dir):
if not hidden and nm.startswith('.'):
continue
if not relative:
nm = os.path.join(dir, nm)
nodes.append(nm)
nodes.sort()
return nodes
def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
root = os.path.join(root, '') # add slash if not there
for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
if relative:
parent = parent[len(root):]
if dirs and parent:
yield os.path.join(parent, '')
if not hidden:
lfiles = [nm for nm in lfiles if not nm.startswith('.')]
ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place
if files:
lfiles.sort()
for nm in lfiles:
nm = os.path.join(parent, nm)
yield nm
def test(root):
print "* directory listing, with hidden files:"
print ls(root, hidden=True)
print
print "* recursive listing, with dirs, but no hidden files:"
for f in find(root, dirs=True):
print f
print
if __name__ == "__main__":
test(*sys.argv[1:])
ファイルのみを再帰的にリストするための優れたワンライナーです。これを setup.py package_data ディレクティブで使用しました。
import os
[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]
質問の答えではないことは承知していますが、役に立つかもしれません
Python2の場合
#!/bin/python2
import os
def scan_dir(path):
print map(os.path.abspath, os.listdir(pwd))
Python3の場合
フィルターとマップについては、list() でラップする必要があります。
#!/bin/python3
import os
def scan_dir(path):
print(list(map(os.path.abspath, os.listdir(pwd))))
ここでの推奨事項は、マップとフィルターの使用をジェネレーター式またはリスト内包表記に置き換えることです。
#!/bin/python
import os
def scan_dir(path):
print([os.path.abspath(f) for f in os.listdir(path)])
以下は 1 行の Pythonic バージョンです。
import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]
このコードは、指定されたディレクトリ名のすべてのファイルとディレクトリの絶対パスを一覧表示します。
ここに別のオプションがあります。
os.scandir(path='.')
パスで指定されたディレクトリ内のエントリ (ファイル属性情報とともに) に対応する os.DirEntry オブジェクトのイテレータを返します。
例:
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.'):
print(entry.name)
listdir() の代わりに scandir() を使用すると、ファイル タイプまたはファイル属性情報も必要とするコードのパフォーマンスが大幅に向上します。, オペレーティング システムがディレクトリをスキャンするときにこの情報を提供すると、os.DirEntry オブジェクトによってこの情報が公開されるためです。すべての os.DirEntry メソッドはシステム コールを実行できますが、is_dir() と is_file() は通常、シンボリック リンクのシステム コールのみを必要とします。os.DirEntry.stat() は、Unix では常にシステム コールを必要としますが、Windows ではシンボリック リンクの場合のみ必要です。
#import modules
import os
_CURRENT_DIR = '.'
def rec_tree_traverse(curr_dir, indent):
"recurcive function to traverse the directory"
#print "[traverse_tree]"
try :
dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]
except:
print "wrong path name/directory name"
return
for file_or_dir in dfList:
if os.path.isdir(file_or_dir):
#print "dir : ",
print indent, file_or_dir,"\\"
rec_tree_traverse(file_or_dir, indent*2)
if os.path.isfile(file_or_dir):
#print "file : ",
print indent, file_or_dir
#end if for loop
#end of traverse_tree()
def main():
base_dir = _CURRENT_DIR
rec_tree_traverse(base_dir," ")
raw_input("enter any key to exit....")
#end of main()
if __name__ == '__main__':
main()
参考までに、拡張機能またはextファイルのインポートOSのフィルターを追加します
path = '.'
for dirname, dirnames, filenames in os.walk(path):
# print path to all filenames with extension py.
for filename in filenames:
fname_path = os.path.join(dirname, filename)
fext = os.path.splitext(fname_path)[1]
if fext == '.py':
print fname_path
else:
continue
import os, sys
#open files in directory
path = "My Documents"
dirs = os.listdir( path )
# print the files in given directory
for file in dirs:
print (file)
思い立ったら、これを投入します。ワイルドカード検索を行う単純かつ汚い方法。
import re
import os
[a for a in os.listdir(".") if re.search("^.*\.py$",a)]
以下のコードは、ディレクトリとそのディレクトリ内のファイルをリストします。
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
これが古い質問であることは承知しています。これは、liunx マシンを使用している場合に私が見つけた優れた方法です。
import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
私と一緒に作業したものは、上記のSalehの回答からの修正版のようなものです。
コードは次のとおりです。
"dir = 'given_directory_name' filenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]"
その間 os.listdir()
ファイル名とディレクトリ名のリストを生成するのには適していますが、それらの名前を取得したらさらに多くのことを行いたくなることがよくあります。Python3 では、 パスライブラリ 他の家事が簡単になります。あなたも私と同じようにそれが好きかどうかを見てみましょう。
dir の内容をリストするには、Path オブジェクトを構築し、イテレータを取得します。
In [16]: Path('/etc').iterdir()
Out[16]: <generator object Path.iterdir at 0x110853fc0>
物の名前のリストだけが必要な場合:
In [17]: [x.name for x in Path('/etc').iterdir()]
Out[17]:
['emond.d',
'ntp-restrict.conf',
'periodic',
ディレクトリだけが必要な場合:
In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]
Out[18]:
['emond.d',
'periodic',
'mach_init.d',
そのツリー内のすべての conf ファイルの名前が必要な場合は、次のようにします。
In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]
Out[20]:
['ntp-restrict.conf',
'dnsextd.conf',
'syslog.conf',
1K 以上のツリー内の conf ファイルのリストが必要な場合:
In [23]: [x.name for x in Path('/etc').glob('**/*.conf') if x.stat().st_size > 1024]
Out[23]:
['dnsextd.conf',
'pf.conf',
'autofs.conf',
相対パスの解決が簡単になります。
In [32]: Path('../Operational Metrics.md').resolve()
Out[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')
パスを使用したナビゲーションは非常に明確です (予想外ではありますが)。
In [10]: p = Path('.')
In [11]: core = p / 'web' / 'core'
In [13]: [x for x in core.iterdir() if x.is_file()]
Out[13]:
[PosixPath('web/core/metrics.py'),
PosixPath('web/core/services.py'),
PosixPath('web/core/querysets.py'),