Q:

Python: How to modify for a memory-friendly code

I have the following code to search all utf16 encoded .ini files and search their contents but RAM usage immediately jumps from 1.3GB to 3.9GB that cause my PC to crash. What certain module is the reason here? How can I do better for this?
import os
import chardet
import shutil

dir_path = os.path.dirname(os.path.realpath(__file__)) 
string = r"\v5."

def get_encoding(filename):
    filebyte = open(filename, 'rb')
    detect_encoding = chardet.detect(filebyte.read())        
    file_encoding = detect_encoding['encoding']
    filebyte.close()
    return file_encoding

for root, dirs, files in os.walk(dir_path): 
    for file in files: 
        if file.endswith('.ini'):
            filepath = root+'/'+str(file)
            encoding = get_encoding(filepath)
            if encoding == "UTF-16":
                print (filepath)

A:

Hmmm... I agree with @jmd_dk it seems very strange to have .ini files that are that big.
Is there some other code that's going on that's not posted?
So, it doesn't appear that your code is memory limiting unless you have an .ini file over a 1Gb.
In any case I would recommend using pathlib to make things a bit easier for you.
import os
import chardet
import shutil
from pathlib import Path

dir_path = Path(__file__).parent

for item in dir_path.rglob('*.ini'):  # recursive glob
    with item.open('rb') as filebytes:
        detected = chardet.detect(filebytes.read())
        if detected['encoding'] == 'UTF-16':
            print(item)

