Forum: Poser Python Scripting


Subject: Useful Code Snippets

structure opened this issue on Jun 27, 2019 ยท 94 posts


structure posted Mon, 25 October 2021 at 6:24 AM Forum Coordinator

Find a word / phrase in any file without loading the file into memory; 

import mmap
import os


class Dialogs:
    def get_folder( self, start = "" ):
        style = wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON
        dialog = wx.DirDialog( None, 'Select a Folder ', start , style )
        return dialog.GetPath() if dialog.ShowModal() == wx.ID_OK else None

    def get_text( self, title = "", message = "" ):
        style = wx.ID_OK|wx.ID_CANCEL
        TE_dialog = wx.TextEntryDialog( None, message, title, "", style )
        TE_dialog.SetValue("")
        return TE_dialog.GetValue() if TE_dialog.ShowModal() == wx.ID_OK else None


class File_Ops:
    def find_in_files( self, root, listoffiles, thing_to_find ):
        found_in_files = False
        thing_to_find = bytes( thing_to_find, encoding = 'utf8' )
        for file in listoffiles:
            file = os.path.join(root, file)
            with open(file) as f:
                s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
                if s.find( thing_to_find ) != -1:
                    print(f'{thing_to_find} found in {file}.')
                    found_in_files = True
                elif len(list_of_files) == 1 and s.find(thing_to_find) == -1:
                    print(f'{thing_to_find} not found in {file}.')
                else:
                    pass
        if not found_in_files:
            print(f'{thing_to_find} not found.')

title = "find in files"
root = Dialogs().get_folder()
list_of_files = os.listdir(root)
thing_to_find = Dialogs().Get_text(title, "Find What ?",  )
if root and list_of_files and thing_to_find:
    File_Ops().find_in_files(root, list_of_files, thing_to_find)

Locked Out