Oct-13-2017, 08:23 PM
I'm trying to convert a log file to CSV and am stumped.
This is a representation of the real file. This would be two records and they're always separated by a blank line. The number of fields in the first line is not always the same and the total number of lines per block is dependent on the last field of the first line.
My output should be
Here's the output from running it
This is a representation of the real file. This would be two records and they're always separated by a blank line. The number of fields in the first line is not always the same and the total number of lines per block is dependent on the last field of the first line.
Quote:1 | 2 | 3
a b c
x y z
1 | 2 | 4
aa bb cc
xx yy zz
My output should be
Output:1 | 2 | 3 | a b c x y z
1 | 2 | 4 | aa bb cc xx yy zz
So far all I've managed to do is stick a pipe after every line which is not really what I want to do (and it leaves a trailing | at the end)#!/usr/bin/python import sys usage = " usage: " + sys.argv[0] + " <inputfile> <outputfile>" if len(sys.argv)!=3: print(usage) sys.exit(1) inFile = sys.argv[1] outFile = sys.argv[2] outStr = '' with open(inFile) as f: for line in f: line = line.strip('\n') if len(line.strip()) == 0: outStr += (line + '\n') else: outStr += (line + '|') f = open(outFile, 'w') f.write(outStr.strip()) f.close()
Here's the output from running it
Output:1 | 2 | 3|a b c|x y z|
1 | 2 | 4|aa bb cc|xx yy zz|
Am I on the right track? Any better ways to do this?