lundi 8 avril 2019

Elegant ways to generate lists based on conditions using information from a input file

I have a file which looks like following,

file= '/user/home/file.txt'

file

[SKY]
/user/home/repo/study

[EARTH]
/user/home/learn/objects

[LOCAL]
/user/home/teach/files

[SAMP]
VKP
RNP
SAS

[TYPE]
HGH

[SAMP_ID]
VKP_TP_MA
RNP_TP_NA
SAS_SAS

[ENV]
....

Now I need to transfer the items from [SAMP] and [SAMP_ID] to a list. This is what I am doing which is giving what I need. But any better or elegant solution would be great.

So my lists are samp and samp_id, and here is the solution and I am using currently,

samp = []
samp_id = []
sampSection = False
samp_idection  =  False

for line in open(file, 'r'):
    if len(line.strip()) == 0:
        sampSection = False
        continue
    if line.strip() == '[SAMP]':
        sampSection = True
        continue
    elif line.startswith('['):
        sampSection = False
        continue
    if sampSection:
        samp.append(line.strip())
        continue

for line in open(file, 'r'):
    if len(line.strip()) == 0:
        samp_idection = False
        continue
    if line.strip() == '[SAMP_ID]':
        samp_idection = True
        continue
    elif line.startswith('['):
        samp_idection = False
        continue
    if samp_idection:
        samp_id.append(line.strip())
        continue

And samp and samp_id looks as follows,

samp =['VKP','RNP', 'SAS']
samp_id=['VKP_TP_MA','RNP_TP_NA', 'SAS_SAS']

It would be great if there is any simpler solutions in this case.

Aucun commentaire:

Enregistrer un commentaire