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))
そのようなものが必要です。
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
print file
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
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でもこのモジュールのバックポートをインストールすることができます (例えば、
condaや
pipを使うことで)。 しかし、古いバージョンのPythonでもバックポートをインストールすることができます(つまり、
condaや
pipを使用して)。 (すなわち、
condaや
pip`を使って) 古いバージョンのPythonでも、このモジュールのバックポートをインストールすることができます。
同じものの他のバージョンもありますが、結果は若干異なります。
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
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
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)
1万個のファイルを含むディレクトリを検索している場合、リストへの追加は効率が悪くなります。 結果を生成することがより良い解決策です。 の方が良い解決策です。 また、出力をPandas Dataframeに変換する関数も用意しました。
python インポート os インポートリ import pandas as pd import numpy as np
def findFilesInFolderYield(path, extension, containsTxt=''', subFolders = True, excludeText = ''')。 となります。 フォルダ内の拡張子タイプのすべてのファイルを見つける再帰的な関数です(オプションですべてのサブフォルダ内のファイルも)
パス。 ファイルを見つけるためのベースディレクトリ の拡張子を指定します。 検索するファイルの拡張子。 例えば txt'。 正規表現。 または 'lsd'. を使用して ls1, ls2, ls3 などと一致させます。 containsTxt. 文字列のリスト、このテキストが含まれている場合にのみファイルを検索します。 もし ''なら無視します。 (または空白) subFoldersを使用しています。 ブール。 True の場合、パスの下にあるすべてのサブフォルダ内のファイルを検索します。 Falseの場合、指定されたフォルダ内のファイルのみを検索します。 excludeText. テキスト文字列。 39;''であれば無視します。 テキスト文字列がパス内にあれば除外します。 の場合は無視します。 if type(containsTxt) == str.
containsTxt = [containsTxt]
myregexobj = re.compile('I.S.A.S.A. 拡張子 + 拡張子 + '$') # ファイルの拡張子が最後にあり、前に .
で始まることを確認します。
ファイルのパーミッションの問題だと思います。 のエントリを os.scandir(path) で検索します。 if entry.is_file() と myregexobj.search(entry.path) の場合。
bools = [entry.pathにtxtがあり、かつ(excludeText == ''. または、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('アクセスできません。
def findFilesInFolderYieldandGetDf(path, extension, containsTxt, subFolders = True, excludeText = '')。 quot;"". findFilesInFolderYieldから返されたデータを変換し、Pandas Dataframeを作成します。 フォルダ内の拡張子タイプのすべてのファイルを見つける再帰関数(オプションですべてのサブフォルダも)。
パス。 ファイルを見つけるためのベースディレクトリ の拡張子を指定します。 検索するファイルの拡張子。 例えば txt'。 正規表現。 または 'lsd'. を使用して ls1, ls2, ls3 などと一致させます。 containsTxt. 文字列のリスト、このテキストが含まれている場合にのみファイルを検索します。 もし ''なら無視します。 (または空白) subFoldersを使用しています。 ブール。 True の場合、パスの下にあるすべてのサブフォルダ内のファイルを検索します。 Falseの場合、指定されたフォルダ内のファイルのみを検索します。 excludeText. テキスト文字列。 39;''であれば無視します。 テキスト文字列がパス内にあれば除外します。 """.
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'.
containsTxt=[] path = 'C:C:myFolder'. df = findFilesInFolderYieldandGetDf(path, ext, containsTxt, subFolders = True)
すべての 'txt を取得するには、以下のようにします。 フォルダ内の全ての 'dataPath'. フォルダ内のすべてのファイル名をピソ的な方法でリストとして取得するには
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
特定の拡張子を持つファイルの完全なファイルパスのリストを取得するために、サブディレクトリを持たない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
私は、[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)
サブディレクトリを持つ機能的なソリューション。
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"))))