読み込み - python ワイルドカード
ディレクトリのすべてのファイルを一覧表示するにはどうすればよいですか? (20)
Pythonでディレクトリのすべてのファイルをリストし、 list
追加するにはどうしたらいいですか?
Python 2と3でファイルのリストを取得する
私もここで短いビデオを作った: Python:ディレクトリ内のファイルのリストを取得する方法
os.listdir()
または.....現在のディレクトリ(Python 3)内のすべてのファイル(およびディレクトリ)を取得する方法
Python 3のカレントディレクトリにファイルを置く最も簡単な方法はこれです。 それは本当に簡単です。 os
モジュールとlistdir()関数を使用すると、そのディレクトリにファイルがあります(そして最終的にはディレクトリにありますが、サブディレクトリにファイルはありません。後でそれについて話す)。
>>> import os
>>> arr = os.listdir()
>>> arr
['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
globを使う
私は、同じタイプのファイルを選択したり、共通するものを選択したりするのがより簡単であることがわかりました。 次の例を見てください:
import glob
txtfiles = []
for file in glob.glob("*.txt"):
txtfiles.append(file)
リストの理解を使う
import glob
mylist = [f for f in glob.glob("*.txt")]
os.path.abspathで完全なパス名を取得する
あなたが気づいたように、あなたは上のコードでファイルの完全なパスを持っていません。 絶対パスが必要な場合は、 os.listdir()
から取得したファイルを引数として、 os.listdir()
というos.path
モジュールの別の関数を使用できます。 私たちは後でチェックするので、完全なパスを持つ他の方法があります(私はmexmexによって提案されたように、_getfullpathnameにabspathをabspath
)。
>>> import os
>>> files_path = [os.path.abspath(x) for x in os.listdir()]
>>> files_path
['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']
walkのあるすべてのサブディレクトリにあるファイルタイプの絶対パス名を取得する
私はこれが非常に多くのディレクトリ内のものを見つけるのに便利だと私は名前を覚えていないファイルを見つけるのを助けた:
import os
# Getting the current work directory (cwd)
thisdir = os.getcwd()
# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
for file in f:
if ".docx" in file:
print(os.path.join(r, file))
os.listdir():カレントディレクトリのファイルを取得する(Python 2)
Python 2では、現在のディレクトリにあるファイルのリストが必要な場合は、引数として '。'を指定する必要があります。 os.listdirメソッドのos.getcwd()を使用します。
>>> import os
>>> arr = os.listdir('.')
>>> arr
['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
ディレクトリツリーに移動するには
>>> # Method 1
>>> x = os.listdir('..')
# Method 2
>>> x= os.listdir('/')
ファイルを取得する:特定のディレクトリ(Python 2と3)のos.listdir()
>>> import os
>>> arr = os.listdir('F:\\python')
>>> arr
['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
os.listdir()で特定のサブディレクトリのファイルを取得する
import os
x = os.listdir("./content")
os.walk( '。') - 現在のディレクトリ
>>> import os
>>> arr = next(os.walk('.'))[2]
>>> arr
['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']
globモジュール - すべてのファイル
import glob
print(glob.glob("*"))
out:['content', 'start.py']
next(os.walk( '。'))とos.path.join( 'dir'、 'file')
>>> import os
>>> arr = []
>>> for d,r,f in next(os.walk("F:\_python")):
>>> for file in f:
>>> arr.append(os.path.join(r,file))
...
>>> for f in arr:
>>> print(files)
>output
F:\\_python\\dict_class.py
F:\\_python\\programmi.txt
next(os.walk( 'F:\') - 完全なパスを取得する - リストの理解
>>> [os.path.join(r,file) for r,d,f in next(os.walk("F:\\_python")) for file in f]
['F:\\_python\\dict_class.py', 'F:\\_python\\programmi.txt']
os.walk - フルパスを取得 - サブディレクトリにあるすべてのファイル
x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]
>>>x
['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']
os.listdir() - txtファイルのみを取得する
>>> arr_txt = [x for x in os.listdir() if x.endswith(".txt")]
>>> print(arr_txt)
['work.txt', '3ebooks.txt']
glob - txtファイルのみを取得する
>>> import glob
>>> x = glob.glob("*.txt")
>>> x
['ale.txt', 'alunni2015.txt', 'assenze.text.txt', 'text2.txt', 'untitled.txt']
globを使用してファイルの完全なパスを取得する
ファイルの絶対パスが必要な場合:
>>> from path import path
>>> from glob import glob
>>> x = [path(f).abspath() for f in glob("F:\*.txt")]
>>> for f in x:
... print(f)
...
F:\acquistionline.txt
F:\acquisti_2018.txt
F:\bootstrap_jquery_ecc.txt
globのその他の使用
ディレクトリ内のすべてのファイルが必要な場合:
>>> x = glob.glob("*")
os.path.isfileを使用してリスト内のディレクトリを避ける
import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]
print(listOfFiles)
> output
['a simple game.py', 'data.txt', 'decorator.py']
pathlibを使って(Python 3.4)
import pathlib
>>> flist = []
>>> for p in pathlib.Path('.').iterdir():
... if p.is_file():
... print(p)
... flist.append(p)
...
error.PNG
exemaker.bat
guiprova.mp3
setup.py
speak_gui2.py
thumb.PNG
リストの理解を使用する場合
>>> flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]
* pathlib.Path( "。")の代わりにpathlib.Path()も使用できます。
pathlib.Path()でglobメソッドを使用する
import pathlib
py = pathlib.Path().glob("*.py")
for file in py:
print(file)
出力:
stack_overflow_list.py
stack_overflow_list_tkinter.py
os.walkですべてのファイルのみを取得する
import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
for f in t:
y.append(f)
>>> y
['append_to_list.py', 'data.txt', 'data1.txt', 'data2.txt', 'data_180617', 'os_walk.py', 'READ2.py', 'read_data.py', 'somma_defaltdic.py', 'substitute_words.py', 'sum_data.py', 'data.txt', 'data1.txt', 'data_180617']
次のファイルのみを取得し、ディレクトリ内を歩く
>>> import os
>>> x = next(os.walk('F://python'))[2]
>>> x
['calculator.bat','calculator.py']
次のディレクトリだけを取得し、ディレクトリ内を歩く
>>> import os
>>> next(os.walk('F://python'))[1] # for the current dir use ('.')
['python3','others']
walkですべてのサブディレクトリ名を取得する
>>> for r,d,f in os.walk("F:\_python"):
... for dirs in d:
... print(dirs)
...
.vscode
pyexcel
pyschool.py
subtitles
_metaprogramming
.ipynb_checkpoints
Python 3.5からのos.scandir()
>>> import os
>>> x = [f.name for f in os.scandir() if f.is_file()]
>>> x
['calculator.bat','calculator.py']
# Another example with scandir (a little variation from docs.python.org)
# This one is more efficient than os.listdir.
# In this case, it shows the files only in the current directory
# where the script is executed.
>>> import os
>>> with os.scandir() as i:
... for entry in i:
... if entry.is_file():
... print(entry.name)
...
ebookmaker.py
error.PNG
exemaker.bat
guiprova.mp3
setup.py
speakgui4.py
speak_gui2.py
speak_gui3.py
thumb.PNG
>>>
Ex。 1:サブディレクトリにはいくつのファイルがありますか?
この例では、すべてのディレクトリとそのサブディレクトリに含まれるファイルの数を検索します。
import os
def count(dir, counter=0):
"returns number of files in dir and subdirs"
for pack in os.walk(dir):
for f in pack[2]:
counter += 1
return dir + " : " + str(counter) + "files"
print(count("F:\\python"))
> output
>'F:\\\python' : 12057 files'
例2:ディレクトリからすべてのファイルを別のディレクトリにコピーするには?
あなたのコンピュータでタイプのすべてのファイル(デフォルト:pptx)を見つけて、それらを新しいフォルダにコピーするためのスクリプト。
import os
import shutil
from path import path
destination = "F:\\file_copied"
# os.makedirs(destination)
def copyfile(dir, filetype='pptx', counter=0):
"Searches for pptx (or other - pptx is the default) files and copies them"
for pack in os.walk(dir):
for f in pack[2]:
if f.endswith(filetype):
fullpath = pack[0] + "\\" + f
print(fullpath)
shutil.copy(fullpath, destination)
counter += 1
if counter > 0:
print("------------------------")
print("\t==> Found in: `" + dir + "` : " + str(counter) + " files\n")
for dir in os.listdir():
"searches for folders that starts with `_`"
if dir[0] == '_':
# copyfile(dir, filetype='pdf')
copyfile(dir, filetype='txt')
> Output
_compiti18\Compito Contabilità 1\conti.txt
_compiti18\Compito Contabilità 1\modula4.txt
_compiti18\Compito Contabilità 1\moduloa4.txt
------------------------
==> Found in: `_compiti18` : 3 files
Ex。 3:txtファイル内のすべてのファイルを取得する方法
すべてのファイル名でtxtファイルを作成する場合は次のようにします。
import os
mylist = ""
with open("filelist.txt", "w", encoding="utf-8") as file:
for eachfile in os.listdir():
mylist += eachfile + "\n"
file.write(mylist)
例:ハードドライブのすべてのファイルを含むtxt
"""We are going to save a txt file with all the files in your directory.
We will use the function walk()
"""
import os
# see all the methods of os
# print(*dir(os), sep=", ")
listafile = []
percorso = []
with open("lista_file.txt", "w", encoding='utf-8') as testo:
for root, dirs, files in os.walk("D:\\"):
for file in files:
listafile.append(file)
percorso.append(root + "\\" + file)
testo.write(file + "\n")
listafile.sort()
print("N. of files", len(listafile))
with open("lista_file_ordinata.txt", "w", encoding="utf-8") as testo_ordinato:
for file in listafile:
testo_ordinato.write(file + "\n")
with open("percorso.txt", "w", encoding="utf-8") as file_percorso:
for file in percorso:
file_percorso.write(file + "\n")
os.system("lista_file.txt")
os.system("lista_file_ordinata.txt")
os.system("percorso.txt")
1つのテキストファイル内のC:\\のすべてのファイル
これは前のコードの短いバージョンです。 別の位置から開始する必要がある場合は、ファイルの検索を開始するフォルダを変更します。 このコードは、完全なパスを持つファイルで、500.000行以下のもので、コンピュータ上のテキストファイルに50 MBを生成します。
import os
with open("file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk("C:\\"):
for file in f:
filewrite.write(f"{r + file}\n")
特定の種類のファイルを検索する機能
輸入OS
def searchfiles(extension='.ttf'):
"Create a txt file with all the file of a type"
with open("file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk("C:\\"):
for file in f:
if file.endswith(extension):
filewrite.write(f"{r + file}\n")
# looking for ttf file (fonts)
searchfiles('ttf')
パート1
予備メモ
- 質問テキストにはファイルとディレクトリの用語が明確に区別されていますが、実際にはディレクトリは特別なファイルであると主張する人もいます
- 「 ディレクトリのすべてのファイル 」という文は、次の2つの方法で解釈できます。
- すべての直接 (またはレベル1)子孫のみ
- ディレクトリツリー全体(サブディレクトリ内のものを含む)内のすべての子孫は、
質問があったとき、私はPython 2がLTSバージョンであると想像しましたが、コードサンプルはPython 3 ( .5 )で実行されます( Python 2をできるだけ守っています;投稿するつもりのPythonは、特に指定がない限りv3.5.4のものです)。 これは、 「 リストに追加する 」という質問の別のキーワードに関連する結果をもたらします 。
- Python 2.2以前のバージョンでは、シーケンス(iterables)はほとんどがリスト(タプル、セットなど)で表されていました。
- Python 2.2では、 ジェネレータ ( [Python]:Generators )のコンセプト( [Python]: yieldステートメント )が導入されました。 時間が経つにつれて、リストで返された/働いた関数の生成元の対応が表示され始めました
- Python 3では、ジェネレータはデフォルトの動作です
- 今、私はリストを返すことが依然として必須か(またはジェネレータも同様に)、
list
ジェネレータをlist
コンストラクタに渡すかどうかはわかりませんが、list
を作成して消費します。 以下の例は[Python]の違いを示しています: map ( function、iterable、... )
Python 2.7.10 (default, Mar 8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> m = map(lambda x: x, [1, 2, 3]) # Just a dummy lambda function >>> m, type(m) ([1, 2, 3], <type 'list'>) >>> len(m) 3
Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> m = map(lambda x: x, [1, 2, 3]) >>> m, type(m) (<map object at 0x000001B4257342B0>, <class 'map'>) >>> len(m) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'map' has no len() >>> lm0 = list(m) # Construct a list out of the generator >>> lm0, type(lm0) ([1, 2, 3], <class 'list'>) >>> >>> lm1 = list(m) # Construct a list out of the same generator >>> lm1, type(lm1) # Empty list this time - generator already consumed ([], <class 'list'>)
この例は、次の構造を持つroot_dirというディレクトリに基づいています(この例はWinですが、 Ux ( Lnx )のフォルダツリーも複製しています)。
E:\Work\Dev\\q003207219>tree /f "root_dir" Folder PATH listing for volume Work Volume serial number is 00000029 3655:6FED E:\WORK\DEV\\Q003207219\ROOT_DIR │ file0 │ file1 │ ├───dir0 │ ├───dir00 │ │ │ file000 │ │ │ │ │ └───dir000 │ │ file0000 │ │ │ ├───dir01 │ │ file010 │ │ file011 │ │ │ └───dir02 │ └───dir020 │ └───dir0200 ├───dir1 │ file10 │ file11 │ file12 │ ├───dir2 │ │ file20 │ │ │ └───dir20 │ file200 │ └───dir3
ソリューション
プログラム的アプローチ:
[Python]:os。 listdir ( path = '。' )
pathで指定されたディレクトリ内のエントリの名前を含むリストを返します。 リストは任意の順序であり、特別なエントリ
'.'
は含まれません'.'
と'..'
...>>> import os >>> root_dir = "root_dir" # Path relative to current dir (os.getcwd()) >>> >>> os.listdir(root_dir) # List all the items in root_dir ['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1'] >>> >>> [item for item in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, item))] # Filter the items and only keep files (strip out directories) ['file0', 'file1']
より精巧な例( code_os_listdir.py )を次に示します。
import os from pprint import pformat def _get_dir_content(path, include_folders, recursive): entries = os.listdir(path) for entry in entries: entry_with_path = os.path.join(path, entry) if os.path.isdir(entry_with_path): if include_folders: yield entry_with_path if recursive: for sub_entry in _get_dir_content(entry_with_path, include_folders, recursive): yield sub_entry else: yield entry_with_path def get_dir_content(path, include_folders=True, recursive=True, prepend_folder_name=True): path_len = len(path) + len(os.path.sep) for item in _get_dir_content(path, include_folders, recursive): yield item if prepend_folder_name else item[path_len:] def _get_dir_content_old(path, include_folders, recursive): entries = os.listdir(path) ret = list() for entry in entries: entry_with_path = os.path.join(path, entry) if os.path.isdir(entry_with_path): if include_folders: ret.append(entry_with_path) if recursive: ret.extend(_get_dir_content_old(entry_with_path, include_folders, recursive)) else: ret.append(entry_with_path) return ret def get_dir_content_old(path, include_folders=True, recursive=True, prepend_folder_name=True): path_len = len(path) + len(os.path.sep) return [item if prepend_folder_name else item[path_len:] for item in _get_dir_content_old(path, include_folders, recursive)] def main(): root_dir = "root_dir" ret0 = get_dir_content(root_dir, include_folders=True, recursive=True, prepend_folder_name=True) lret0 = list(ret0) print(ret0, len(lret0), pformat(lret0)) ret1 = get_dir_content_old(root_dir, include_folders=False, recursive=True, prepend_folder_name=False) print(len(ret1), pformat(ret1)) if __name__ == "__main__": main()
注 :
- 2つの実装があります。
- ジェネレータを使用するもの(もちろん、この例では結果をリストにすぐに変換するので役に立たないようです)
- 古典的なもの( _oldで終わる関数名)
- 再帰が使用されます(サブディレクトリに入るために)
- 各実装には、次の2つの機能があります。
- アンダースコア ( _ )で始まるもの: "private"(直接呼び出されるべきではない) - すべての作業
- パブリックなもの(前のラッパー):返されたエントリから最初のパス(必要な場合)を取り除くだけです。 それは醜い実装ですが、私がこの時点で来ることができる唯一のアイデアです
- パフォーマンスに関しては、ジェネレータは一般的には少し速く( 作成と繰り返しの両方の時間を考慮して)、再帰関数ではテストしませんでした。また、内部ジェネレータを介して関数内部を反復しています。フレンドリーです
- 異なる結果を得るために引数を使って遊ぶ
出力 :
(py35x64_test) E:\Work\Dev\\q003207219>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" "code_os_listdir.py" <generator object get_dir_content at 0x000001BDDBB3DF10> 22 ['root_dir\\dir0', 'root_dir\\dir0\\dir00', 'root_dir\\dir0\\dir00\\dir000', 'root_dir\\dir0\\dir00\\dir000\\file0000', 'root_dir\\dir0\\dir00\\file000', 'root_dir\\dir0\\dir01', 'root_dir\\dir0\\dir01\\file010', 'root_dir\\dir0\\dir01\\file011', 'root_dir\\dir0\\dir02', 'root_dir\\dir0\\dir02\\dir020', 'root_dir\\dir0\\dir02\\dir020\\dir0200', 'root_dir\\dir1', 'root_dir\\dir1\\file10', 'root_dir\\dir1\\file11', 'root_dir\\dir1\\file12', 'root_dir\\dir2', 'root_dir\\dir2\\dir20', 'root_dir\\dir2\\dir20\\file200', 'root_dir\\dir2\\file20', 'root_dir\\dir3', 'root_dir\\file0', 'root_dir\\file1'] 11 ['dir0\\dir00\\dir000\\file0000', 'dir0\\dir00\\file000', 'dir0\\dir01\\file010', 'dir0\\dir01\\file011', 'dir1\\file10', 'dir1\\file11', 'dir1\\file12', 'dir2\\dir20\\file200', 'dir2\\file20', 'file0', 'file1']
- 2つの実装があります。
[Python]:os。 scandir ( path = '。' ) ( !!! Python 3.5 + !!!以前のバージョンでは別のモジュール( Python 2にも移植されていました)だと思いますが)
pathで指定されたディレクトリ内のエントリに対応するos.DirEntryオブジェクトのイテレータをos.DirEntryます。 エントリは任意の順序で生成され、特別なエントリ
'.'
と'..'
は含まれていません。lists.ir()の代わりにscandir()を使用すると、 os.DirEntryオブジェクトはオペレーティングシステムがディレクトリをスキャンするときにこの情報を公開するため、ファイルタイプまたはファイル属性情報も必要とするコードのパフォーマンスを大幅に向上させる可能性があります。 すべてのos.DirEntryメソッドはシステムコールを実行できますが、 is_dir()およびis_file()は通常、シンボリックリンクのシステムコールのみを必要とします。 os.DirEntry.stat()は、Unix上では常にシステムコールが必要ですが、Windows上のシンボリックリンクにのみ必要です。
>>> import os >>> root_dir = os.path.join(".", "root_dir") # Explicitly prepending current directory >>> root_dir '.\\root_dir' >>> >>> scandir_iterator = os.scandir(root_dir) >>> scandir_iterator <nt.ScandirIterator object at 0x00000268CF4BC140> >>> [item.path for item in scandir_iterator] ['.\\root_dir\\dir0', '.\\root_dir\\dir1', '.\\root_dir\\dir2', '.\\root_dir\\dir3', '.\\root_dir\\file0', '.\\root_dir\\file1'] >>> >>> [item.path for item in scandir_iterator] # Will yield an empty list as it was consumed by previous iteration (automatically performed by the list comprehension) [] >>> >>> scandir_iterator = os.scandir(root_dir) # Reinitialize the generator >>> for item in scandir_iterator : ... if os.path.isfile(item.path): ... print(item.name) ... file0 file1
注 :
- これは
os.listdir
似ていos.listdir
- しかし、それはまた、より柔軟性があり(より多くの機能を提供する)、より多くのPython IC(そして場合によってはより速い)
- これは
[Python]:os。 散歩 ( top、topdown = True、onerror =なし、followlinks = False )
ツリーをトップダウンまたはボトムアップのいずれかの方向に移動して、ディレクトリツリーにファイル名を生成します。 ディレクトリtop (ルート自体を含む)をルートとするツリー内の各ディレクトリについて、3タプル(
dirpath
、dirnames
、filenames
)をdirnames
しfilenames
。>>> import os >>> root_dir = os.path.join(os.getcwd(), "root_dir") # Specify the full path >>> root_dir 'E:\\Work\\Dev\\\\q003207219\\root_dir' >>> >>> walk_generator = os.walk(root_dir) >>> root_dir_entry = next(walk_generator) # First entry corresponds to the root dir (that was passed as an argument) >>> root_dir_entry ('E:\\Work\\Dev\\\\q003207219\\root_dir', ['dir0', 'dir1', 'dir2', 'dir3'], ['file0', 'file1']) >>> >>> root_dir_entry[1] + root_dir_entry[2] # Display the dirs and the files (that are direct descendants) in a single list ['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1'] >>> >>> [os.path.join(root_dir_entry[0], item) for item in root_dir_entry[1] + root_dir_entry[2]] # Display all the entries in the previous list by their full path ['E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0', 'E:\\Work\\Dev\\\\q003207219\\root_dir\\dir1', 'E:\\Work\\Dev\\\\q003207219\\root_dir\\dir2', 'E:\\Work\\Dev\\\\q003207219\\root_dir\\dir3', 'E:\\Work\\Dev\\\\q003207219\\root_dir\\file0', 'E:\\Work\\Dev\\\\q003207219\\root_dir\\file1'] >>> >>> for entry in walk_generator: # Display the rest of the elements (corresponding to every subdir) ... print(entry) ... ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0', ['dir00', 'dir01', 'dir02'], []) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0\\dir00', ['dir000'], ['file000']) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0\\dir00\\dir000', [], ['file0000']) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0\\dir01', [], ['file010', 'file011']) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0\\dir02', ['dir020'], []) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0\\dir02\\dir020', ['dir0200'], []) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir0\\dir02\\dir020\\dir0200', [], []) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir1', [], ['file10', 'file11', 'file12']) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir2', ['dir20'], ['file20']) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir2\\dir20', [], ['file200']) ('E:\\Work\\Dev\\\\q003207219\\root_dir\\dir3', [], [])
注 :
- シーンの下では、
os.listdir
(os.scandir
使用可能な場合) - それは、サブフォルダで繰り返されることによって重労働を起こす
- シーンの下では、
[Python]:glob。glob(pathname、*、recursive = False)([Python]:glob .iglob(pathname、*、recursive = False))
一致するパス名の可能性、空のリストを返しパス名をパス指定を含む文字列でなければなりません。pathnameは絶対(like
/usr/src/Python-1.5/Makefile
)でも相対(like../../Tools/*/*.gif
)でもかまいませんし、シェルスタイルのワイルドカードを含むことができます。壊れたシンボリックリンクが結果に含まれます(シェルのように)。
...
バージョン3.5で変更されました: "**
"を使って再帰的globsをサポートしました。>>> import glob, os >>> wildcard_pattern = "*" >>> root_dir = os.path.join("root_dir", wildcard_pattern) # Match every file/dir name >>> root_dir 'root_dir\\*' >>> >>> glob_list = glob.glob(root_dir) >>> glob_list ['root_dir\\dir0', 'root_dir\\dir1', 'root_dir\\dir2', 'root_dir\\dir3', 'root_dir\\file0', 'root_dir\\file1'] >>> >>> [item.replace("root_dir" + os.path.sep, "") for item in glob_list] # Strip the dir name and the path separator from begining ['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1'] >>> >>> for entry in glob.iglob(root_dir + "*", recursive=True): ... print(entry) ... root_dir\ root_dir\dir0 root_dir\dir0\dir00 root_dir\dir0\dir00\dir000 root_dir\dir0\dir00\dir000\file0000 root_dir\dir0\dir00\file000 root_dir\dir0\dir01 root_dir\dir0\dir01\file010 root_dir\dir0\dir01\file011 root_dir\dir0\dir02 root_dir\dir0\dir02\dir020 root_dir\dir0\dir02\dir020\dir0200 root_dir\dir1 root_dir\dir1\file10 root_dir\dir1\file11 root_dir\dir1\file12 root_dir\dir2 root_dir\dir2\dir20 root_dir\dir2\dir20\file200 root_dir\dir2\file20 root_dir\dir3 root_dir\file0 root_dir\file1
注 :
- 用途
os.listdir
- 大きな木の場合(特に
recursive
オンの場合)、iglob
優先されます - 名前に基づいた高度なフィルタリングが可能(ワイルドカードのため)
- 用途
[Python]:クラスpathlib。パス(* pathsegments)(!!! Python 3 + !!!バックポートされているかどうかわからない)
>>> import pathlib >>> root_dir = "root_dir" >>> root_dir_instance = pathlib.Path(root_dir) >>> root_dir_instance WindowsPath('root_dir') >>> root_dir_instance.name 'root_dir' >>> root_dir_instance.is_dir() True >>> >>> [item.name for item in root_dir_instance.glob("*")] # Wildcard searching for all direct descendants ['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1'] >>> >>> [os.path.join(item.parent.name, item.name) for item in root_dir_instance.glob("*") if not item.is_dir()] # Display paths (including parent) for files only ['root_dir\\file0', 'root_dir\\file1']
注 :
- これが私たちの目標を達成する一つの方法です
- パスを処理するのはOOPスタイルです
- 多くの機能を提供
[Python]:dircache.listdir(path)(!!!はPython 3で 削除されました!!!)
- しかし、によると$ {} PYTHON_SRC_DIR /Lib/dircache.py:〜#20(+からv2.7.14)、それだけで(薄い)だのラッパー
os.listdir
def listdir(path): """List directory contents, using cache.""" try: cached_mtime, list = cache[path] del cache[path] except KeyError: cached_mtime, list = -1, [] mtime = os.stat(path).st_mtime if mtime != cached_mtime: list = os.listdir(path) list.sort() cache[path] = mtime, list return list
- しかし、によると$ {} PYTHON_SRC_DIR /Lib/dircache.py:〜#20(+からv2.7.14)、それだけで(薄い)だのラッパー
[男性]のopendir(3) / [男性]:READDIR(3) / [男性]:closedirの(3)を介して[パイソン]:ctypes - Pythonのための外部関数ライブラリ(!!! UXの特定!!!)
ctypesはPython用の外部関数ライブラリです。これは、C互換のデータ型を提供し、DLLまたは共有ライブラリの関数呼び出しを可能にします。これらのライブラリを純粋なPythonでラップするために使用できます。
code_ctypes.py:
#!/usr/bin/env python3 import sys from ctypes import Structure, \ c_ulonglong, c_longlong, c_ushort, c_ubyte, c_char, c_int, \ CDLL, POINTER, \ create_string_buffer, get_errno, set_errno, cast, sizeof DT_DIR = 4 DT_REG = 8 char256 = c_char * 256 class LinuxDirent64(Structure): _fields_ = [ ("d_ino", c_ulonglong), ("d_off", c_longlong), ("d_reclen", c_ushort), ("d_type", c_ubyte), ("d_name", char256), ] LinuxDirent64Ptr = POINTER(LinuxDirent64) libc_dll = CDLL(None) opendir = libc_dll.opendir readdir = libc_dll.readdir closedir = libc_dll.closedir libc_dll.__errno_location.restype = POINTER(c_int) errno_loc_func = libc_dll.__errno_location def _get_errno(): return "errno: {:d}({:d})".format(get_errno(), errno_loc_func().contents.value) def get_dir_content(path): ret = [path, list(), list()] dir_stream = opendir(create_string_buffer(path.encode())) if (dir_stream == 0): print("opendir returned NULL ({:s})".format(_get_errno())) return ret set_errno(0) dirent_addr = readdir(dir_stream) while dirent_addr: dirent_ptr = cast(dirent_addr, LinuxDirent64Ptr) dirent = dirent_ptr.contents name = dirent.d_name.decode() if dirent.d_type & DT_DIR: if name not in (".", ".."): ret[1].append(name) elif dirent.d_type & DT_REG: ret[2].append(name) dirent_addr = readdir(dir_stream) if get_errno() or errno_loc_func().contents.value: print("readdir returned NULL ({:s})".format(_get_errno())) closedir(dir_stream) return ret def main(): print("{:s} on {:s}\n".format(sys.version, sys.platform)) root_dir = "root_dir" entries = get_dir_content(root_dir) print(entries) if __name__ == "__main__": main()
注 :
- それから3つの機能をロードするlibcの詳細は、チェックのために((現在のプロセスにロードされた)、それらを呼び出す?[スタックオーバーフロー]:どのように私は、ファイルは、Pythonを使用して存在しているかどうかをチェックします(CristiFatiの答え@を) -アイテムから最後のノート#4 。)。これは、このアプローチをPython / Cのエッジに非常に近いものにします
-
LinuxDirent64
私のマシンのdirent.hからのctypes表現です(定数です):Ubtu 16 x64(4.10.0-40-genericとlibc6-dev:amd64)。他の味/バージョンでは、構造体の定義が異なる場合があり、そうであればctypesエイリアスを更新する必要があります。そうでない場合は、未定義ビヘイビアstruct dirent64
DT_*
-
errno_loc_func
(そしてそれに関連するすべてのもの)はerrno
エラーの場合にfuncsが設定され、その値をチェックする必要があるからです。明らかに、get_errno
動作しません(無効な名前でopendir
返しますNULL
が、get_errno
まだ0を返します)、またはまだそれを把握していません - それは、その
os.walk
形式でデータを返します。私はそれを再帰的にするのは気にしませんでしたが、既存のコードから始めれば、それはかなり簡単な作業です - Winでもすべてが実行可能です。データ(ライブラリ、関数、構造体、定数など)は異なります
出力 :
[email protected]:~/work//q003207219$ ./code_ctypes.py 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux ['root_dir', ['dir3', 'dir2', 'dir0', 'dir1'], ['file0', 'file1']]
[ActiveState]:win32file.FindFilesW(!!! Win特有の!!!)
Windows Unicode APIを使用して、一致するファイル名のリストを取得します。API FindFirstFileW / FindNextFileW / Find close関数へのインタフェース。
>>> import os, win32file, win32con >>> root_dir = "root_dir" >>> wildcard = "*" >>> root_dir_wildcard = os.path.join(root_dir, wildcard) >>> entry_list = win32file.FindFilesW(root_dir_wildcard) >>> len(entry_list) # Don't display the whole content as it's too long 8 >>> [entry[-2] for entry in entry_list] # Only display the entry names ['.', '..', 'dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1'] >>> >>> [entry[-2] for entry in entry_list if entry[0] & win32con.FILE_ATTRIBUTE_DIRECTORY and entry[-2] not in (".", "..")] # Filter entries and only display dir names (except self and parent) ['dir0', 'dir1', 'dir2', 'dir3'] >>> >>> [os.path.join(root_dir, entry[-2]) for entry in entry_list if entry[0] & (win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_ATTRIBUTE_ARCHIVE)] # Only display file "full" names ['root_dir\\file0', 'root_dir\\file1']
注 :
-
win32file.FindFilesW
一部である[GitHubの]:Windows用のPython(pywin32)の拡張機能で、PythonのオーバーラッパーWINAPI秒 - ドキュメンテーションのリンクはhttps://www.activestate.com です。pywin32公式のマニュアルが見つかりませんでした。
-
- そのトリックを行う(他の)サードパーティのパッケージをインストールしてください
- おそらく、上記のうちの1つ(またはそれ以上)に依存します(おそらくわずかなカスタマイズで)
ノート(上のものについて):
- コードは移植可能であることを意味します(マークされた特定の領域をターゲットとする場所を除く)
- プラットフォーム(Ux、Win、)
- Pythonバージョン(2、3、)
- 使用される「ツール」がこの方向に柔軟であるという事実を示すために、上記のバリアント全体で複数のパススタイル(絶対、親戚)が使用されています
-
os.listdir
及びos.scandir
使用opendir
/readdir
/closedir
([MSDN]:FindFirstFile関数 / [MSDN]:FindNextFile機能 / [MSDN]:FindClose関数() "を介して$ {PYTHON_SRC_DIR} /Modules/posixmodule.c ") -
win32file.FindFilesW
それらの(Win固有の)関数も同様に使用します( " $ {PYWIN32_SRC_DIR} /win32/src/win32file.i "を介して)。 -
get_dir_content
(ポイント#1から)これらのアプローチのいずれかを使用して実装することができます(いくつかはより多くの作業を必要とします)- (だけではなく、ファイルの一部の高度なフィルタリング対 DIR)が行うことができる:例えば
include_folders
引数は別のもの(例えば置き換えることができるfilter_func
引数にパスを取る関数になります):filter_func=lambda x: True
(これは何を削除しません)そして内側にget_dir_content
何かのように:if not filter_func(entry_with_path): continue
(関数は一つのエントリのために失敗した場合、それはスキップされます)が、より複雑なコードとなり、もはやそれは実行に時間がかかります
- (だけではなく、ファイルの一部の高度なフィルタリング対 DIR)が行うことができる:例えば
- ノートベネ!再帰が使用されているので、私は私のラップトップ(上のいくつかのテストをしたことを言及しなければならないのWin 10 x64のこの問題とは全く関係のない)、および再帰レベルが中にどこかの値に達した(990 .. 1000)範囲(recursionlimit 1000年- (デフォルト))、私は :) を得た。ディレクトリツリーがその制限を超えている場合(私はFSの専門家ではないので、それが可能かどうかわかりません)、それが問題になる可能性があります。
私はこの分野での経験がないので再帰制限を増やそうとしなかったことを言及しなければならない(OSでスタックを増やす前にどれくらい増やすことができるかレベル)ですが、理論上は、dirの深さが可能な限り高い再帰制限(そのマシン上)より大きい場合、常に失敗する可能性があります。 - コードサンプルは、説明目的のみのものです。それは私が(私はないと思うの取り扱い口座エラーに入れなかったことを意味
try
/except
/else
/finally
(:できるだけシンプルで短いそれを維持する理由がある)ブロック)は、そのコードが堅牢ではありません。以下のために生産、エラー処理も追加する必要があります
第1部の終わり1
事実のように1 Homeのポスト(質問/答え)制限がある30000文字(:自分の限界を知る:[SE.Meta]質問のタイトル、記事、画像及び使用されるリンクの最大長は何ですか?)、答えは2つに分割されました。[SO]にもアクセスしてください:ディレクトリのすべてのファイルを一覧表示するにはどうすればいいですか?(@ CristiFatiの答え - "パート2")。
os.listdir()
は、ディレクトリにあるすべてのファイルとディレクトリを取得します。
ファイルだけが必要な場合は、 os.path
を使用してこれをフィルタリングするか、
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
os.walk()
を使用すると、訪れたディレクトリごとに2つのリストが生成され、ファイルとディレクトリに分割されます。 一番上のディレクトリだけが必要な場合は、最初に生成されたものを破ることができます
from os import walk
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
最後に、この例のように、あるリストを別のリストに追加するには、 .extend()
または
>>> q = [1, 2, 3]
>>> w = [4, 5, 6]
>>> q = q + w
>>> q
[1, 2, 3, 4, 5, 6]
個人的には、 .extend()
ディレクトリとそのすべてのサブディレクトリから完全なファイルパスを取得する
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
- 上記の関数で提供したパスには、ルートディレクトリに2つ、サブフォルダに3つのファイルが含まれていました。 次のようなことができるようになりました:
リストを印刷する
print full_file_paths
を出力します:-
['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']
-
必要に応じて、コンテンツを開いて読むことができます。また、以下のコードのように、拡張子が.datのファイルのみにフォーカスすることもできます。
for f in full_file_paths:
if f.endswith(".dat"):
print f
/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat
絶対ファイルパスのリストを返すが、サブディレクトリに再帰しない
L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]
Python 3.4+のもう一つの非常に読みやすい変形は、pathlib.Path.globを使用しています:
from pathlib import Path
folder = '/foo'
[f for f in Path(folder).glob('*') if f.is_file()]
シンボリックリンクではないPythonソースファイルだけを探し、すべてのサブディレクトリで探すなど、より具体的にするのは簡単です:
[f for f in Path(folder).glob('**/*.py') if not f.is_symlink()]
ディレクトリの内容を表示するには、 os
モジュールを使用する必要があります。 os.listdir(".")
は、ディレクトリのすべての内容を返します。 結果を反復してリストに追加します。
import os
content_list = []
for content in os.listdir("."): # "." means current directory
content_list.append(content)
print content_list
ディレクトリをパラメータとしてfindfiles()を実行すると、そのディレクトリ内のすべてのファイルのリストが返されます。
import os
def findfiles(directory):
objects = os.listdir(directory) # find all objects in a dir
files = []
for i in objects: # check if very object in the folder ...
if os.path.isfile(os.path.join(directory, i)): # ... is a file.
files.append(i) # if yes, append it.
return files
バージョン3.4以降、これにはイテレータがos.listdir()
おり、 os.listdir()
よりもos.listdir()
効率的です:
pathlib
: バージョン3.4で新たに pathlib
れました。
>>> import pathlib
>>> [p for p in pathlib.Path('.').iterdir() if p.is_file()]
PEP 428によると、 pathlib
ライブラリの目的は、ファイルシステムのパスを処理するためのクラスの単純な階層と、ユーザーが共通の操作を行うことです。
os.scandir()
: バージョン3.5で os.scandir()
。
>>> import os
>>> [entry for entry in os.scandir('.') if entry.is_file()]
os.listdir()
はバージョン3.5のos.scandir()
代わりにos.walk()
使用し、 PEP 471に従って速度が2〜20倍に増加したことに注意してください。
以下のShadowRangerのコメントを読むことをお勧めします。
別のファイルタイプを使用する場合、または完全なディレクトリを取得する場合は、この関数を使用します。
import os
def createList(foldername, fulldir = True, suffix=".jpg"):
file_list_tmp = os.listdir(foldername)
#print len(file_list_tmp)
file_list = []
if fulldir:
for item in file_list_tmp:
if item.endswith(suffix):
file_list.append(os.path.join(foldername, item))
else:
for item in file_list_tmp:
if item.endswith(suffix):
file_list.append(item)
return file_list
私はadamkの答えが本当に好きで、同じ名前のモジュールからglob()
を使うことを示唆していました。 これにより、 *
sとのパターンマッチングが可能になります。
しかし、他の人がコメントの中で指摘しているように、 glob()
は一貫性のないスラッシュの指示につきまとうことができます。 これを助けるために、 os.path
モジュールでjoin()
およびexpanduser()
関数を使用することをお勧めします。おそらくos
モジュールのgetcwd()
関数も使用することをお勧めします。
例として:
from glob import glob
# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')
上記はひどいです - パスはハードコードされており、ドライブ名と\
sがパスにハードコードされている間にWindows上でのみ動作します。
from glob import glob
from os.path import join
# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))
上記はうまくいきますが、Windows上で見つけられることが多く、他のOSではあまり見つからないフォルダー名のUsers
依存しています。 また、 admin
は特定の名前のadmin
依存しています。
from glob import glob
from os.path import expanduser, join
# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))
これは、すべてのプラットフォームで完全に機能します。
プラットフォーム間で完璧に動作し、少し違うことをする素晴らしい例です。
from glob import glob
from os import getcwd
from os.path import join
# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))
これらのサンプルが、標準のPythonライブラリモジュールで見つかるいくつかの関数の力を理解するのに役立ちたいと考えています。
私はそれがパターンマッチングと展開を行うので、 glob
モジュールの使用を好む。
import glob
print(glob.glob("/home/adam/*.txt"))
照会されたファイルを含むリストが返されます:
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
findの Python実装を探しているなら、これは私が頻繁に使うレシピです:
from findtools.find_files import (find_files, Match)
# Recursively find all *.sh files in **/usr/bin**
sh_files_pattern = Match(filetype='f', name='*.sh')
found_files = find_files(path='/usr/bin', match=sh_files_pattern)
for found_file in found_files:
print found_file
だから、私はPyPI packageを作りました.GitHub リポジトリもあります。私は誰かがこのコードのために潜在的に有用であると考えていることを願っています
@adamkによる回答を参照すると、@Anti Earthによるスラッシュの矛盾のコメントに対する私のosの検出方法です
import sys
import os
from pathlib import Path
from glob import glob
platformtype = sys.platform
if platformtype == 'win32':
slash = "\\"
if platformtype == 'darwin':
slash = "/"
# TODO: How can I list all files of a directory in Python and add them to a list?
# Step 1 - List all files of a directory
# Method 1: Find only pre-defined filetypes (.txt) and no subfiles, answer provided by @adamk
dir1 = "%sfoo%sbar%s*.txt" % (slash)
_files = glob(dir1)
# Method 2: Find all files and no subfiles
dir2 = "%sfoo%sbar%s" % (slash)
_files = (x for x in Path("dir2").iterdir() if x.is_file())
# Method 3: Find all files and all subfiles
dir3 = "%sfoo%sbar" % (slash)
_files = (x for x in Path('dir3').glob('**/*') if x.is_file())
# Step 2 - Add them to a list
files_list = []
for eachfiles in _files:
files_basename = os.path.basename(eachfiles)
files_list.append(files_basename)
print(files_list)
['file1.txt', 'file2.txt', .... ]
私はあなたがリストにbasenamesだけを必要としていると仮定しています。
方法1の複数のファイル形式を事前定義するには、このpostを参照してください。
ソースパスとファイルタイプを入力として提供できるサンプルライナーを提供します。このコードは、拡張子がcsvのファイル名のリストを返します。使用する。すべてのファイルを返す必要がある場合 これにより、サブディレクトリも再帰的にスキャンされます。
[y for x in os.walk(sourcePath) for y in glob(os.path.join(x[0], '*.csv'))]
必要に応じて、ファイル拡張子とソースパスを変更します。
パフォーマンスを気にするなら、試してみてくださいscandir
。Python 2.xでは、手動でインストールする必要があります。例:
# python 2.x
import scandir
import sys
de = scandir.scandir(sys.argv[1])
while 1:
try:
d = de.next()
print d.path
except StopIteration as _:
break
これは、巨大なディレクトリをスキャンする必要があるときに多くの時間を節約し、巨大なリストをバッファリングする必要はなく、ただ一つをフェッチするだけです。また、再帰的に行うこともできます。
def scan_path(path):
de = scandir.scandir(path)
while 1:
try:
e = de.next()
if e.is_dir():
scan_path(e.path)
else:
print e.path
except StopIteration as _:
break
def list_files(path):
# returns a list of names (with extension, without full path) of all files
# in folder path
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
files.append(name)
return files
import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
if len(list[i]) != check:
temp.append(list[i-1])
check = len(list[i])
else:
i = i + 1
count = count - 1
print temp
import os
lst=os.listdir(path)
os.listdirは、pathで指定されたディレクトリ内のエントリの名前を含むリストを返します。
import os
os.listdir("somedirectory")
"somedirectory"内のすべてのファイルとディレクトリのリストを返します。