Harshitha Goli Harshitha Goli - 3 months ago 10
Python Question

Extract part of file and print using python

I want to extract part of the file content . Which starts with ("head"
and ends with ("arraydat"

content of file:

(record
( "head"
(record
( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
[ "" ]
)
( "numel" 192)
( "mux" 1)
( "freq" 3400000)
( "date" 63602497416.093)
( "focus" 0.066)
( "probID" 574)
( "te" 0)
( "therm" 0)
( "bipolar" "N/A")
( "maker" "YMS")
( "PartNum" 5418916)
( "numrow" 1)
)
)
( "arraydat"
(record
( "FL6" 1625283.947393933)
( "FH6" 4932875.254089763)
( "FL20" 1283607.261269079)
( "FH20" 5673248.882271254)
( "Fc" 3279079.600741847)
( "BW" 100.8695033187829)
( "PW6" 3.316821935120381E-007)
( "PW20" 9.740000000000003E-007)
( "PW30" 1.456E-006)
( "PW40" 2.628000000000001E-006)
( "LG" -46.35823409318354)
( "TOF" -1.363659434369523E-008)
)


I need to extract the content of a file after "head" and before "arraydat".
I have tried this command but no luck

import re
with open('sample.txt','r') as new_file:
data = new_file.read()
pattern = re.compile(r'\s[(]\s"head"[\s\S]*?\s[(]\s"arraydat"')
stringtext = re.findall(pattern, data)
print(stringtext)


Output should look like this:

( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
[ "" ]
)
( "numel" 192)
( "mux" 1)
( "freq" 3400000)
( "date" 63602497416.093)
( "focus" 0.066)
( "probID" 574)
( "te" 0)
( "therm" 0)
( "bipolar" "N/A")
( "maker" "YMS")
( "PartNum" 5418916)
( "numrow" 1)
)
)

Answer
data = []
read = False

for line in open('test.dat'):
    if line.strip() == '( "head"':
        read = True
        continue
    elif line.strip() == '( "arraydat"':
        read = False
    if read:
        data.append(line.rstrip())

print('\n'.join(data))
Comments