Pythonで拡張子が.txtのディレクトリ内の全てのファイルを検索する

pythonで拡張子が.txtのディレクトリ内のすべてのファイルを検索するにはどうしたらいいですか?

ソリューション

glob`]1を使うことができます。

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

または、単に os.listdir:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

また、ディレクトリをトラバースしたい場合は、[os.walk`][3]を使用します。

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

[3]: https://docs.python.org/2/library/os.html#os.walk

解説 (21)

glob](http://docs.python.org/library/glob.html)を使用します

>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']
解説 (4)

そのようなものが必要です。

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file
解説 (4)

こんな感じのものが効いてきます。

>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']
解説 (2)
import os

path = 'mypath/path' 
files = os.listdir(path)

files_txt = [i for i in files if i.endswith('.txt')]
解説 (0)

os.walk()][1]が好きです。

import os, os.path

for root, dirs, files in os.walk(dir):
    for f in files:
        fullpath = os.path.join(root, f)
        if os.path.splitext(fullpath)[1] == '.txt':
            print fullpath

もしくは発電機で。

import os, os.path

fileiter = (os.path.join(root, f)
    for root, _, files in os.walk(dir)
    for f in files)
txtfileiter = (f for f in fileiter if os.path.splitext(f)[1] == '.txt')
for txt in txtfileiter:
    print txt

[1]: http://docs.python.org/library/os.html

解説 (0)

単純にpathlibglobの1を利用すればよい。

import pathlib

list(pathlib.Path('your_directory').glob('*.txt'))

またはループしています。

for txt_file in pathlib.Path('your_directory').glob('*.txt'):
    # do something with "txt_file"

再帰的に実行したい場合は .glob('**/*.txt) を使用することができます。


1pathlibモジュールは python 3.4 の標準ライブラリに含まれていましたが、古いバージョンの Python でもバックポートをインストールすることができます。 しかし、古いバージョンのPythonでもこのモジュールのバックポートをインストールすることができます (例えば、condapipを使うことで)。 しかし、古いバージョンのPythonでもバックポートをインストールすることができます(つまり、condapipを使用して)。 (すなわち、condapip`を使って) 古いバージョンのPythonでも、このモジュールのバックポートをインストールすることができます。

解説 (4)

同じものの他のバージョンもありますが、結果は若干異なります。

以下に、同じものの他のバージョンを示します。

import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories 
    print f

glob.glob1() ### glob.glob1()

print glob.glob1("/mydir", "*.tx?")  # literal_directory, basename_pattern

### [fnmatch.filter()][2] ### [fnmatch.filter()][2]を使用します。

import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files

[1]: http://docs.python.org/library/glob.html#glob.iglob [2]: http://docs.python.org/library/fnmatch.html#fnmatch.filter

解説 (3)

path.pyも別の方法です。 https://github.com/jaraco/path.py

from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
    print f
解説 (2)

Pythonはこれを行うためのツールをすべて持っています。

import os

the_dir = 'the_dir_that_want_to_search_in'
all_txt_files = filter(lambda x: x.endswith('.txt'), os.listdir(the_dir))
解説 (1)

Python v3.5.5+の場合

os.scandirを再帰関数で使う高速なメソッド。 フォルダとサブフォルダ内の指定された拡張子を持つ全てのファイルを検索します。

import os

def findFilesInFolder(path, pathList, extension, subFolders = True):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:        Base directory to find files
    pathList:    A list that stores all paths
    extension:   File extension to find
    subFolders:  Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    """

    try:   # Trapping a OSError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and entry.path.endswith(extension):
                pathList.append(entry.path)
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                pathList = findFilesInFolder(entry.path, pathList, extension, subFolders)
    except OSError:
        print('Cannot access ' + path +'. Probably a permissions error')

    return pathList

dir_name = r'J:\myDirectory'
extension = ".txt"

pathList = []
pathList = findFilesInFolder(dir_name, pathList, extension, True)

2019年4月更新

1万個のファイルを含むディレクトリを検索している場合、リストへの追加は効率が悪くなります。 結果を生成することがより良い解決策です。 の方が良い解決策です。 また、出力をPandas Dataframeに変換する関数も用意しました。

python インポート os インポートリ import pandas as pd import numpy as np

def findFilesInFolderYield(path, extension, containsTxt=''', subFolders = True, excludeText = ''')。 となります。 フォルダ内の拡張子タイプのすべてのファイルを見つける再帰的な関数です(オプションですべてのサブフォルダ内のファイルも)

パス。 ファイルを見つけるためのベースディレクトリ の拡張子を指定します。 検索するファイルの拡張子。 例えば txt'。 正規表現。 または 'lsd&#39. を使用して ls1, ls2, ls3 などと一致させます。 containsTxt. 文字列のリスト、このテキストが含まれている場合にのみファイルを検索します。 もし '&#39なら無視します。 (または空白) subFoldersを使用しています。 ブール。 True の場合、パスの下にあるすべてのサブフォルダ内のファイルを検索します。 Falseの場合、指定されたフォルダ内のファイルのみを検索します。 excludeText. テキスト文字列。 39;''であれば無視します。 テキスト文字列がパス内にあれば除外します。 の場合は無視します。 if type(containsTxt) == str.

文字列でリストにない場合

containsTxt = [containsTxt]

myregexobj = re.compile('I.S.A.S.A. 拡張子 + 拡張子 + '$') # ファイルの拡張子が最後にあり、前に .

で始まることを確認します。

OSErrorまたはFileNotFoundErrorをトラップします.

ファイルのパーミッションの問題だと思います。 のエントリを os.scandir(path) で検索します。 if entry.is_file() と myregexobj.search(entry.path) の場合。

bools = [entry.pathにtxtがあり、かつ(excludeText == '&#39. または、entry.pathにexcludeTextが含まれていない場合)

len(bools)== len(containsTxt) の場合。 yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path

elif entry.is_dir() と subFolders.

ディレクトリであれば、入れ子になった関数として処理を繰り返します。

yield from findFilesInFolderYield(entry.path, extension, containsTxt, subFolders) OSError を ose とした場合を除きます。 print('アクセスできません。

  • パスにアクセスできません。 おそらくパーミッションエラーです ', ose) fnfとしてFileNotFoundErrorを除く。 print(パス +&#39. 見つかりませんでした ', fnf)

def findFilesInFolderYieldandGetDf(path, extension, containsTxt, subFolders = True, excludeText = '')。 quot;"&quot. findFilesInFolderYieldから返されたデータを変換し、Pandas Dataframeを作成します。 フォルダ内の拡張子タイプのすべてのファイルを見つける再帰関数(オプションですべてのサブフォルダも)。

パス。 ファイルを見つけるためのベースディレクトリ の拡張子を指定します。 検索するファイルの拡張子。 例えば txt'。 正規表現。 または 'lsd&#39. を使用して ls1, ls2, ls3 などと一致させます。 containsTxt. 文字列のリスト、このテキストが含まれている場合にのみファイルを検索します。 もし '&#39なら無視します。 (または空白) subFoldersを使用しています。 ブール。 True の場合、パスの下にあるすべてのサブフォルダ内のファイルを検索します。 Falseの場合、指定されたフォルダ内のファイルのみを検索します。 excludeText. テキスト文字列。 39;''であれば無視します。 テキスト文字列がパス内にあれば除外します。 ""&quot.

fileSizes, accessTimes, modificationTimes, creationTimes , paths = zip(*findFilesInFolderYield(path, extension, containsTxt, subFolders)) df = pd.DataFrame({) 'FLS_File_Size':fileSizes. FLS_File_Access_Dateལ:accessTimes. 'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]')を使用しています。 このような場合には、ファイルを作成する前に、ファイルを作成する前に、ファイルを作成する前に、ファイルを作成する前に、ファイルを作成する前に、ファイルを作成してください。 FLS_File_PathNameལ:パスを指定します。 })

df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True) df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True) df['FLS_File_Access_Date' ] = pd.to_datetime(df['FLS_File_Access_Date' ],infer_datetime_format=True)

リターンディーエフ

ext = 'txt&#39.

正規表現

containsTxt=[] path = 'C:C:myFolder&#39. df = findFilesInFolderYieldandGetDf(path, ext, containsTxt, subFolders = True)

解説 (0)

すべての 'txt を取得するには、以下のようにします。 フォルダ内の全ての 'dataPath&#39. フォルダ内のすべてのファイル名をピソ的な方法でリストとして取得するには

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles
解説 (0)
import os
import sys 

if len(sys.argv)==2:
    print('no params')
    sys.exit(1)

dir = sys.argv[1]
mask= sys.argv[2]

files = os.listdir(dir); 

res = filter(lambda x: x.endswith(mask), files); 

print res
解説 (0)

特定の拡張子を持つファイルの完全なファイルパスのリストを取得するために、サブディレクトリを持たない1つのフォルダに対して、どのソリューションが最も速いかを確認するためにテストを行いました(Python 3.6.4, W7x64)。

簡潔に言うと、このタスクでは os.listdir() が最も速く、次のベストの1.7倍の速さである。 (休憩あり)の1.7倍、pathlibの2.7倍、os.scandir()の3.2倍、globの3.3倍の速さです。 これらの結果は、再帰的な結果が必要な場合には変化することを覚えておいてください。 以下のメソッドをコピー&ペーストする場合は、.lower()を追加してください。

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    os.chdir(path)
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )
        break

print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))

結果が出ました。

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274
解説 (2)

これを試すと、すべてのファイルを再帰的に検索することができます。

import glob, os
os.chdir("H:\\wallpaper")# use whatever you directory 

#double\\ no single \

for file in glob.glob("**/*.psd", recursive = True):#your format
    print(file)
解説 (3)

fnmatchを使用してください。 https://docs.python.org/2/library/fnmatch.html

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file
解説 (0)

このコードは私の生活をシンプルにしてくれます。

import os
fnames = ([file for root, dirs, files in os.walk(dir)
    for file in files
    if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
    ])
for fname in fnames: print(fname)
解説 (0)

というフォルダから".txt&quot.ファイル名の配列を取得するには ファイル名の配列を取得するには、同じディレクトリにある"data&quot. というフォルダから"data"ファイル名の配列を取得するには、通常は次のような簡単なコードを使用します。

import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]
解説 (0)

私は、[fnmatch][1]と上の方法を使うことをお勧めします。 この方法では、以下のいずれかを見つけることができます。

1.Name.txt。 2.名前.txt。 3.名前.txt; 2.名前.txt; 3.名前.txt; 4.

.

import fnmatch
import os

    for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
        if fnmatch.fnmatch(file.upper(), '*.TXT'):
            print(file)

[1]: https://docs.python.org/2/library/fnmatch.html

解説 (0)

サブディレクトリを持つ機能的なソリューション。

from fnmatch import filter
from functools import partial
from itertools import chain
from os import path, walk

print(*chain(*(map(partial(path.join, root), filter(filenames, "*.txt")) for root, _, filenames in walk("mydir"))))
解説 (2)