dimanche 4 mars 2018

Parsing srtructure file Python

I want to understand the peculiarity of using the construction Case When in Python. I have a text file of the following kind:

Head 1
a 10
a 14
a 15
Head 4
a 32
a 55
a 79
Head 53
a 22
a 33
Head 33
a 11
a 66
Head 32
a 88
a 89
a 88
End

I want parse and structure this file to next plane:

Head 1, a 10
Head 1, a 14
Head 1, a 15
Head 4, a 32
Head 4, a 55
Head 4, a 79
Head 53, a 22
Head 53, a 33
Head 33, a 11
Head 33, a 66
Head 32, a 88
Head 32, a 89
Head 32, a 88

The first thing I learned when I started to learn Python this is the absence of the case when.

The way that I try:

array = []
with open('C:/file/1.txt') as f:
 for line in f:
  if line[0:4] == 'Head':
   Header = line
   print(Header)
  elif line[0:1] == 'a':
   Subheader = line
   print(Subheader)
  else:
   continue

Is it possible to decompose the data in the required format using this approach? Thanks

Aucun commentaire:

Enregistrer un commentaire