vendredi 16 décembre 2016

Double if conditional in the line.startswith strategy

I have a data.dat file with this format:

REAL PART 

FREQ     1.6     5.4     2.1    13.15    13.15    17.71
FREQ     51.64   51.64   82.11  133.15   133.15   167.71

.
.
.

IMAGINARY PART 

FREQ     51.64    51.64     82.12   132.15    129.15    161.71
FREQ     5.64     51.64     83.09   131.15    120.15    160.7

Within the REAL PART block,

I would like to split each line that starts with FREQ.

I have managed to:

1) split lines and extract the value of FREQ and

2) append this result to a list of lists, and

3) create a final list, All_frequencies:

FREQ = []
fname ='data.dat'
f = open(fname, 'r')
for line in f:
    if line.startswith(' FREQ'):
    FREQS = line.split()
    FREQ.append(FREQS)

print 'Final FREQ = ', FREQ
All_frequencies = list(itertools.chain.from_iterable(FREQ))
print 'All_frequencies = ', All_frequencies

The problem with this code is that it also extracts the IMAGINARY PART values of FREQ. Only the REAL PART values of FREQ would have to be extracted.

I have tried to make something like:

if line.startswith('REAL PART'):
   if line.startswith('IMAGINARY PART'):
      code...

or:

if line.startswith(' REAL') and line.startswith(' FREQ'):
   code...

But this does not work. I would appreciate if you could help me

Aucun commentaire:

Enregistrer un commentaire