My file is like this Heading1, Heading2, Heading3, Heading4, Heading5
Alpha, Beta, Gama, Face, Human
Dog, Camel, Horse, Lion
################# Summary ###############################
Heading6 = V8CA02TB Heading7 = 8R1 Heading8 = ENVS2F12SLB2 Heading9 = mkern2 Heading10 = 1654774930624 Heading11 = 09 13:42:10 2022
I want to make file like this
Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, Heading7, Heading8, Heading9, Heading10, Heading11
Alpha, Beta, Gama, Face, Human, V8CA02TB, 8R1, ENVS2F12SLB2, mkern2, 1654774930624, 09 13:42:10 2022
Cat, Dog, Camel, Horse, Lion, V8CA02TB, 8R1, ENVS2F12SLB2, mkern2, 1654774930624, 09 13:42:10 2022
I have to do that on multiple files and then combine all the files in one text file
Any help will be appreciated.
Advertisement
Answer
This will parse your format.
with open('x.data') as fin: header = None rows = [] extra = [] for line in fin: if len(line) < 5: continue if not header: header = line.strip().split(',') elif 'Summary' in line: break else: rows.append( line.strip().split(',') ) for line in fin: line = line.strip() if not line: continue left,_,right = line.partition(' = ') header.append( left ) extra.append( right ) with open('out.data', 'w') as fout: print( ','.join(header), file=fout ) for row in rows: print( ','.join(row+extra), file=fout )
Output:
A,B,C,D,E,F,G,H,I,J,K Alpha, Beta, Gama, Face, Human,V8CA02TB,8R1,ENVS2F12SLB2,mkern2,1654774930624, 09 13:42:10 2022 Cat, Dog, Camel, Horse, Lion,V8CA02TB,8R1,ENVS2F12SLB2,mkern2,1654774930624, 09 13:42:10 2022
Combining multiple files is easy, even without Python.