How to only read words within brackets/ parentheses (in .txt file) using Python

pankaj.jangid at gmail.com pankaj.jangid at gmail.com
Thu Sep 5 06:10:36 EDT 2019


A S <aishan0403 at gmail.com> writes:

> I understand that reading lines in .txt files would look something like this in Python:
>
>
> with open('filename','r') as fd:
>    lines = fd.readlines()
>
>
> However, how do I run my code to only read the words in my .txt files that are within each balanced parenthesis?
>
> I am not sure how to go about it, let's say my .txt file contents lines like this:
>
> kkkkk;
>
> select xx("xE'", PUT(xx.xxxx.),"'") jdfjhf:jhfjj from xxxx_x_xx_L ;
> quit; 
>
> The main idea is to read only these portions of the .txt file (i.e. Those within parentheses):
>

This should work for the outer parenthesis:

import re

p = re.compile(r"\((.+)\)", re.VERBOSE)

with open('filename','r') as fd:
    lines = fd.readlines()
    for line in lines:
        m = p.findall(line)
        for s in m:
            print(s)


-- 
Pankaj Jangid



More information about the Python-list mailing list