os.listdir का उपयोग कर नामों की सूची आवंटित करने से बचने का सही तरीका ओएस स्तर के फ़ंक्शन का उपयोग करना है क्योंकि @ चार्ल्स डफी ने कहा।
यह अन्य पद से प्रेरित होकर: List files in a folder as a stream to begin process immediately
मैं विशिष्ट ओपी सवाल हल करने के लिए कैसे जोड़ा जाता है और समारोह की फिर से प्रवेशी संस्करण का उपयोग किया।
from ctypes import CDLL, c_char_p, c_int, c_long, c_ushort, c_byte, c_char, Structure, POINTER, byref, cast, sizeof, get_errno
from ctypes.util import find_library
class c_dir(Structure):
"""Opaque type for directory entries, corresponds to struct DIR"""
pass
class c_dirent(Structure):
"""Directory entry"""
# FIXME not sure these are the exactly correct types!
_fields_ = (
('d_ino', c_long), # inode number
('d_off', c_long), # offset to the next dirent
('d_reclen', c_ushort), # length of this record
('d_type', c_byte), # type of file; not supported by all file system types
('d_name', c_char * 4096) # filename
)
c_dirent_p = POINTER(c_dirent)
c_dirent_pp = POINTER(c_dirent_p)
c_dir_p = POINTER(c_dir)
c_lib = CDLL(find_library("c"))
opendir = c_lib.opendir
opendir.argtypes = [c_char_p]
opendir.restype = c_dir_p
readdir_r = c_lib.readdir_r
readdir_r.argtypes = [c_dir_p, c_dirent_p, c_dirent_pp]
readdir_r.restype = c_int
closedir = c_lib.closedir
closedir.argtypes = [c_dir_p]
closedir.restype = c_int
import errno
def listdirx(path):
"""
A generator to return the names of files in the directory passed in
"""
dir_p = opendir(path)
if not dir_p:
raise IOError()
entry_p = cast(c_lib.malloc(sizeof(c_dirent)), c_dirent_p)
try:
while True:
res = readdir_r(dir_p, entry_p, byref(entry_p))
if res:
raise IOError()
if not entry_p:
break
name = entry_p.contents.d_name
if name not in (".", ".."):
yield name
finally:
if dir_p:
closedir(dir_p)
if entry_p:
c_lib.free(entry_p)
if __name__ == '__main__':
import sys
path = sys.argv[1]
max_per_dir = int(sys.argv[2])
for idx, entry in enumerate(listdirx(path)):
if idx >= max_per_dir:
break
print entry
क्या डीपीएक्स छवि अनुक्रम वाले निर्देशिका नामों के बारे में कुछ अलग है? –
यदि आप बड़ी निर्देशिकाओं को क्रमशः पढ़ना चाहते हैं (यानी न केवल रिकर्सन को रोकें, बल्कि उनकी व्यक्तिगत सामग्री भी न पढ़ें), तो आपको http: // stackoverflow पर वर्णित समाधानों की तरह कुछ उपयोग करने की आवश्यकता हो सकती है।कॉम/प्रश्न/44035 9 8/सूची-फाइल-इन-ए-फ़ोल्डर-ए-स्ट्रीम-टू-स्टार्ट-प्रोसेस-तत्काल –
कुछ निर्देशिकाओं में नाम में 'डीपीएक्स' है, लेकिन उनमें से सभी नहीं :(@charles, क्या वह उदाहरण मेरे लिए काम करेगा। अगर मैं एक डीपीएक्स पार करता हूं तो मैं एक सूची से बाहर निकलना चाहता हूं, इस तरह से मैं 100,000 फ़ाइल नामों के माध्यम से पुनरावृत्ति से बच सकता हूं, जो काफी समय लेता है। – Jamie