Jump to content

Simple Example


Recommended Posts

import os
import os.path

class FolderFiles:
	def GetFiles(path,fileExt):
		bPath = FolderFiles.CheckIsPath(path)
		fList = []
		if(bPath):
			for root, dirs, files in os.walk(path):
				for f in files:
					if(FolderFiles.CheckFileExt(f,fileExt)):
						fList.append(f)
		elif(FolderFiles.CheckFileExt(path,fileExt)):
			fList.append(path)
		return fList
	
	def CheckFileExt(filename,fileExt):
		if(fileExt[0] != '.'):
			fileExt = '.' + fileExt
			
		fExtLen = len(fileExt)
		
		if(len(filename) > fExtLen and filename[-fExtLen:] == fileExt):
			return True
		else:
			return False
			
	def CheckIsPath(filename):
		if(os.path.isfile(filename)):
			return Flase
		else:
			return True
			
			

Example :

fList = FolderFiles.GetFiles(u'F:/','py')
for f in fList:
	print(f)

Kind Regards

Zerelth ~ Ellie

  • Love 1

Do not be sorry, be better.

Link to comment
Share on other sites

os walk is pretty slow use this : 

its about 10-25 times faster

# -*- coding: utf-8 -*-
import ctypes
import os
import stat
 
if os.name == 'nt':
    from ctypes import wintypes
 
    INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
    ERROR_FILE_NOT_FOUND = 2
    ERROR_NO_MORE_FILES = 18
    FILE_ATTRIBUTE_DIRECTORY = 16
    FILE_ATTRIBUTE_READONLY = 1
    SECONDS_BETWEEN_EPOCHS = 11644473600  # seconds between 1601-01-01 and 1970-01-01
 
    kernel32 = ctypes.windll.kernel32
 
    _FindFirstFile = kernel32.FindFirstFileW
    _FindFirstFile.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.WIN32_FIND_DATAW)]
    _FindFirstFile.restype = wintypes.HANDLE
 
    _FindNextFile = kernel32.FindNextFileW
    _FindNextFile.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.WIN32_FIND_DATAW)]
    _FindNextFile.restype = wintypes.BOOL
 
    _FindClose = kernel32.FindClose
    _FindClose.argtypes = [wintypes.HANDLE]
    _FindClose.restype = wintypes.BOOL
 
    def _attributes_to_mode(attributes):
        """Convert Win32 dwFileAttributes to st_mode. Taken from CPython's
        Modules/posixmodule.c.
        """
        mode = 0
        if attributes & FILE_ATTRIBUTE_DIRECTORY:
            mode |= stat.S_IFDIR | 0111
        else:
            mode |= stat.S_IFREG
        if attributes & FILE_ATTRIBUTE_READONLY:
            mode |= 0444
        else:
            mode |= 0666
        return mode
 
    def _filetime_to_time(filetime):
        total = filetime.dwHighDateTime << 32 | filetime.dwLowDateTime
        return total / 10000000.0 - SECONDS_BETWEEN_EPOCHS
 
    def _find_data_to_stat(data):
        st_mode = _attributes_to_mode(data.dwFileAttributes)
        st_ino = 0
        st_dev = 0
        st_nlink = 0
        st_uid = 0
        st_gid = 0
        st_size = data.nFileSizeHigh << 32 | data.nFileSizeLow
        st_atime = _filetime_to_time(data.ftLastAccessTime)
        st_mtime = _filetime_to_time(data.ftLastWriteTime)
        st_ctime = _filetime_to_time(data.ftCreationTime)
        st = os.stat_result((st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid,
                             st_size, st_atime, st_mtime, st_ctime))
        return st
 
    def listdir_stat(dirname='.', glob=None):
        dirname = os.path.abspath(dirname)
        filename = os.path.join(dirname, glob or '*')
 
        data = wintypes.WIN32_FIND_DATAW()
        data_p = ctypes.byref(data)
        handle = _FindFirstFile(filename, data_p)
        if handle == INVALID_HANDLE_VALUE:
            error = ctypes.GetLastError()
            if error == ERROR_FILE_NOT_FOUND:
                return
            raise ctypes.WinError()
 
        try:
            while True:
                if data.cFileName not in ('.', '..'):
                    st = _find_data_to_stat(data)
                    yield (data.cFileName, st)
                success = _FindNextFile(handle, data_p)
                if not success:
                    error = ctypes.GetLastError()
                    if error == ERROR_NO_MORE_FILES:
                        break
                    raise ctypes.WinError()
        finally:
            if not _FindClose(handle):
                raise ctypes.WinError()
 
 
# Linux/posix -- this is only half-tested and doesn't work at the moment, but
# leaving here for future use
else:
    import ctypes
    import ctypes.util
 
    class DIR(ctypes.Structure):
        pass
    DIR_p = ctypes.POINTER(DIR)
 
    class dirent(ctypes.Structure):
        _fields_ = (
            ('d_ino', ctypes.c_long),
            ('d_off', ctypes.c_long),
            ('d_reclen', ctypes.c_ushort),
            ('d_type', ctypes.c_byte),
            ('d_name', ctypes.c_char * 256)
        )
    dirent_p = ctypes.POINTER(dirent)
 
    _libc = ctypes.CDLL(ctypes.util.find_library('c'))
    _opendir = _libc.opendir
    _opendir.argtypes = [ctypes.c_char_p]
    _opendir.restype = DIR_p
 
    _readdir = _libc.readdir
    _readdir.argtypes = [DIR_p]
    _readdir.restype = dirent_p
 
    _closedir = _libc.closedir
    _closedir.argtypes = [DIR_p]
    _closedir.restype = ctypes.c_int
 
    DT_DIR = 4
 
    def _type_to_stat(d_type):
        if d_type == DT_DIR:
            st_mode = stat.S_IFDIR | 0111
        else:
            st_mode = stat.S_IFREG
        st = os.stat_result((st_mode, None, None, None, None, None,
                             None, None, None, None))
        return st
 
    def listdir_stat(dirname='.', glob=None):
        dir_p = _opendir(dirname)
        try:
            while True:
                p = _readdir(dir_p)
                if not p:
                    break
                name = p.contents.d_name
                if name not in ('.', '..'):
                    st = _type_to_stat(p.contents.d_type)
                    yield (name, st)
        finally:
            _closedir(dir_p)
  • Love 1
Link to comment
Share on other sites

  • Active Member

is there a need for new class?

import os
wut = raw_input("Folder directory: ")
whichfiles = raw_input("extension: ")
files = os.listdir(wut)
for name in files:
    if name.endswith('.'+whichfiles): print name

print out >>

C:Python27python.exe C:/Users/asus/PycharmProjects/test-esteron.py
Folder directory: c:/python27
extension: py
adminpage.py
constInfo3.py
dll.py
hash_id.py
insa.py
post.py
stealer.py
uiminimap.py
uitaskbar.py
version.py
xd.py
xd2.py

Process finished with exit code 0

or manuel

import os
files = os.listdir("c:/python27")
for name in files:
    if name.endswith('.py'): print name
  • Love 1
Link to comment
Share on other sites

Announcements



×
×
  • Create New...

Important Information

Terms of Use / Privacy Policy / Guidelines / We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.