python - पाइथन में एक्सटेंशन.txt के साथ निर्देशिका में सभी फ़ाइलों को खोजें
file-io (20)
मैं पाइथन में एक्सटेंशन .txt
वाले निर्देशिका में सभी फ़ाइलों को कैसे ढूंढ सकता हूं?
पायथन v3.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)
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
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
आप glob
उपयोग कर सकते हैं:
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
उपयोग os.walk
:
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
आप इस कोड को आजमा सकते हैं:
import glob
import os
os.chdir("D:\...\DirName")
filename_arr={}
i=0
for files in glob.glob("*.txt"):
filename_arr[i] = files
i= i+1
for key,value in filename_arr.items():
print key , value
आप बस pathlib
एस glob
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)
उपयोग कर सकते हैं
1 pathlib
मॉड्यूल को मानक लाइब्रेरी में पायथन 3.4 में शामिल किया गया था। लेकिन आप पुरानी पायथन संस्करणों (यानी conda
या pip
का उपयोग करके) पर भी उस मॉड्यूल के बैक-पोर्ट स्थापित कर सकते हैं: pathlib
और pathlib2
।
उप-निर्देशिकाओं के साथ कार्यात्मक समाधान:
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"))))
उसी निर्देशिका में "डेटा" नामक फ़ोल्डर से ".txt" फ़ाइल नामों की सरणी प्राप्त करने के लिए मैं आमतौर पर कोड की इस सरल रेखा का उपयोग करता हूं:
import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]
ऐसा कुछ काम करेगा:
>>> 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']
कई उपयोगकर्ताओं ने os.walk
उत्तरों के साथ जवाब दिया है, जिसमें सभी फाइलें शामिल हैं लेकिन सभी निर्देशिकाएं और उपनिर्देशिकाएं और उनकी फ़ाइलें भी शामिल हैं।
import os
def files_in_dir(path, extension=''):
"""
Generator: yields all of the files in <path> ending with
<extension>
\param path Absolute or relative path to inspect,
\param extension [optional] Only yield files matching this,
\yield [filenames]
"""
for _, dirs, files in os.walk(path):
dirs[:] = [] # do not recurse directories.
yield from [f for f in files if f.endswith(extension)]
# Example: print all the .py files in './python'
for filename in files_in_dir('./python', '*.py'):
print("-", filename)
या एक ऐसे व्यक्ति के लिए जहां आपको जनरेटर की आवश्यकता नहीं है:
path, ext = "./python", ext = ".py"
for _, _, dirfiles in os.walk(path):
matches = (f for f in dirfiles if f.endswith(ext))
break
for filename in matches:
print("-", filename)
यदि आप किसी और चीज़ के लिए मैचों का उपयोग करने जा रहे हैं, तो आप जनरेटर अभिव्यक्ति के बजाय इसे एक सूची बनाना चाहते हैं:
matches = [f for f in dirfiles if f.endswith(ext)]
पाइथनिक तरीके से सूची के रूप में 'डेटापाथ' फ़ोल्डर के अंदर सभी '.txt' फ़ाइल नाम प्राप्त करने के लिए
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
मुझे os.walk() पसंद है os.walk() :
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
मैंने एक परीक्षण (पायथन 3.6.4, W7x64) एक विशिष्ट एक्सटेंशन वाले फ़ाइलों के लिए पूर्ण फ़ाइल पथों की सूची प्राप्त करने के लिए, एक फ़ोल्डर, कोई उपनिर्देशिका के लिए सबसे तेज़ समाधान देखने के लिए किया है।
इसे कम करने के लिए, इस कार्य के लिए os.listdir()
सबसे तेज़ है और 1.7x जितना तेज़ होगा उतना तेज़: os.walk()
(ब्रेक के साथ!), 2.7x pathlib
जितना pathlib
, 3.2x तेज os.scandir()
और glob
से 3.3x तेज।
कृपया ध्यान रखें, जब आपको रिकर्सिव परिणामों की आवश्यकता होती है तो वे परिणाम बदल जाएंगे। यदि आप नीचे एक विधि कॉपी / पेस्ट करते हैं, तो कृपया .lower () को अन्यथा जोड़ें .EXT .ext के लिए खोज करते समय नहीं मिलेगा।
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
यदि फ़ोल्डर में बहुत सी फाइलें हैं या स्मृति एक बाधा है, तो जनरेटर का उपयोग करने पर विचार करें:
def yield_files_with_extensions(folder_path, file_extension):
for _, _, files in os.walk(folder_path):
for file in files:
if file.endswith(file_extension):
yield file
विकल्प ए: Iterate
for f in yield_files_with_extensions('.', '.txt'):
print(f)
विकल्प बी: सभी प्राप्त करें
files = [f for f in yield_files_with_extensions('.', '.txt')]
यहां कुछ और संस्करण हैं जो थोड़ा अलग परिणाम उत्पन्न करते हैं:
glob.iglob()
import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories
print f
glob.glob1 ()
print glob.glob1("/mydir", "*.tx?") # literal_directory, basename_pattern
fnmatch.filter()
import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files
विशिष्ट एक्सटेंशन वाली फ़ाइलों को ढूंढने के लिए पायथन OS मॉड्यूल का उपयोग करें।
सरल उदाहरण यहां है:
import os
# This is the path where you want to search
path = r'd:'
# this is extension you want to detect
extension = '.txt' # this can be : .jpg .png .xls .log .....
for root, dirs_list, files_list in os.walk(path):
for file_name in files_list:
if os.path.splitext(file_name)[-1] == extension:
file_name_path = os.path.join(root, file_name)
print file_name
print file_name_path # This is the full path of the filter file
extend()
साथ यहां एक है extend()
types = ('*.jpg', '*.png')
images_list = []
for files in types:
images_list.extend(glob.glob(os.path.join(path, files)))
import glob
import os
path=os.getcwd()
extensions=('*.py','*.cpp')
for i in extensions:
for files in glob.glob(i):
print files
import os
path = 'mypath/path'
files = os.listdir(path)
files_txt = [i for i in files if i.endswith('.txt')]
import os
[x for x in os.listdir() if x.endswith(".txt")]
मरने और सब्सक्राइबरों में कितनी फाइलें हैं?
यदि आप जानना चाहते हैं कि एक डीआईआर और उपदियों में कितने फिली हैं:
इस उदाहरण में, हम सभी निर्देशिकाओं और इसकी उप-निर्देशिकाओं में शामिल फ़ाइलों की संख्या की तलाश करते हैं।
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"))
उत्पादन
'एफ: \ पायथन': 12057 फाइलें '