hii..m stuck in an issue...and need a help

I have Try.c file having contents

ValidateFunction()
{
......
......
print
}
....

I want to print data between the braces {....}. Also i do not want to read the contents of file line by line because file is of very big size.How can I get this in Python?

Dani AI

Generated

Two practical ways to extract the { ... } block without loading the whole file into Python memory: use a memory-mapped file (mmap) so the OS pages data on demand, or stream the file in fixed-size chunks while counting braces. These both avoid building one giant string and handle very large files efficiently. Building on ’s brace-count idea (to handle nesting) and ’s note about what “very big” means, the examples below show safe, low-memory approaches.

Memory-mapped approach (fast when you can locate the function name first):

import mmap

def extract_block_by_name(path, name, encoding='utf-8'):
    with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
        pos = mm.find(name.encode())
        if pos == -1:
            return None
        start = mm.find(b'{', pos)
        if start == -1:
            return None
        i = start + 1
        depth = 1
        while depth and i < len(mm):
            b = mm[i:i+1]
            if b == b'{': depth += 1
            elif b == b'}': depth -= 1
            i += 1
        if depth != 0:
            return None
        return mm[start:i].decode(encoding, errors='replace')

Chunked streaming approach (no mmap; portable, good for constrained environments):

def extract_block_stream(path, start_marker=None, chunk_size=65536, encoding='utf-8'):
    with open(path, 'rb') as f:
        if start_marker:
            marker = start_marker.encode()
            tail = b''
            while True:
                chunk = f.read(chunk_size)
                if not chunk: return None
                buf = tail + chunk
                idx = buf.find(marker)
                if idx != -1:
                    f.seek(f.tell() - len(buf) + idx); break
                tail = buf[-(len(marker)-1):]
        depth = 0; collecting = False; out = []
        while True:
            chunk = f.read(chunk_size)
            if not chunk: break
            for byte in chunk:
                if byte == 123:  # ord('{')
                    depth += 1; collecting = True
                elif byte == 125:  # ord('}')
                    depth -= 1
                if collecting: out.append(bytes((byte,)))
                if collecting and depth == 0:
                    return b''.join(out).decode(encoding, errors='replace')
        return None

Notes and pitfalls: these approaches count raw braces; they will be confused by braces appearing inside string literals or comments. For language-aware extraction (C/C++/Java/JS) use a proper parser or parsing library instead of naive counting. Also confirm the file encoding before decoding the extracted bytes (use errors='replace' if unsure). For very large files (multi-GB) mmap is usually the simplest and fastest on modern OSes; chunked streaming is more portable and predictable in low-memory environments.

Recommended Answers

All 2 Replies

You would have to read each record ("lines" is a word processing term and many types of files do not have lines) until you reach the first "{". Then store or print the records until the next "}". Then switch off an indicator. Note that you might want to count the number of "{"s and the number of "}"s to allow for multiple levels, and when they are equal set the indicator to False. To stop the file read would be something like this pseudo-code:

reading = True
while reading:
   fp.readline()
   if "}" is found or end_of_file:
       reading = False

Also the count of { can be used with itertools.groupby to divide the file in parts. Be careful about what you call very big size file. At least the file size should be in hundreds of megabytes to call it huge these days.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.