I have a text file that has some data in the below format, I need to extract it into a CSV file.
CSI_DATA,STA,A8:DA:0C:66:7E:4E,-71,9,0,0,0,0,0,0,0,0,0,-94,0,1,0,2013318,0,82,0,0,2.190914,128,[82 -96 4 0 -34 -8 -33 -7 -32 -7 -33 -9 -32 -8 -32 -7 -31 -8 -30 -7 -30 -8 -30 -7 -30 -7 -28 -7 -27 -8 -25 -9 -26 -9 -25 -7 -23 -8 -22 -8 -21 -7 -19 -9 -18 -9 -19 -7 -17 -8 -15 -8 -13 -8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -8 -4 -9 -4 -10 -5 -10 -6 -11 -5 -11 -5 -12 -4 -14 -5 -14 -4 -12 -5 -16 -6 -16 -7 -18 -6 -18 -6 -19 -5 -21 -5 -22 -7 -22 -5 -24 -4 -25 -4 -25 -4 -28 -6 -30 -4 -30 -6 -34 -7 -35 -7 ]
CSI_DATA,STA,A8:DA:0C:66:7E:4E,-74,11,0,0,0,0,0,0,0,0,0,-94,0,1,0,2023244,0,37,0,0,2.200669,128,[37 80 2 0 -33 0 -36 -3 -35 -4 -35 -3 -35 -3 -31 -4 -26 -5 -24 -4 -18 -9 -15 -9 -11 -10 -5 -12 2 -11 5 -14 9 -16 11 -16 15 -14 14 -14 14 -10 21 -12 18 -9 20 -10 19 -7 16 -3 16 -4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -2 -8 0 -6 1 2 0 11 3 13 6 20 6 25 9 27 12 33 12 34 16 30 16 31 19 28 21 28 22 20 17 18 20 17 17 11 10 8 6 0 5 -3 -1 -1 -9 -5 -19 -9 -20 -1 -23 -8 ]
CSI_DATA,STA,A8:DA:0C:66:7E:4E,-79,9,0,0,0,0,0,0,0,0,0,-93,0,1,0,2284589,0,130,0,0,2.462197,128,[-126 -96 7 0 9 25 10 20 8 20 9 23 9 27 12 26 13 24 13 29 12 25 9 25 11 28 14 26 9 28 9 25 9 22 6 24 6 24 9 22 4 24 4 23 5 24 4 24 3 22 0 22 2 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -9 3 -9 2 -9 0 -11 2 -10 1 -9 0 -10 1 -8 0 -5 2 -4 4 -7 5 -6 5 -3 6 -4 7 -1 7 0 10 2 8 1 12 2 12 1 13 5 16 6 15 5 20 5 18 6 21 9 21 ]
If I directly convert this to CSV, it places all the data in the square bracket in one cell. I want to be able to remove the square brackets and replace all the spaces between the numbers with commas. I tried using various string/character replace methods but to no avail. I'm very new to python so I would appreciate it if you could dumb it down.
CodePudding user response:
You could do it like this:-
with open('csidata.txt') as csi:
with open('csidata.csv', 'w') as csv:
for line in csi:
try:
s = line.index('[')
e = line.index(']', s 1)
t = line[0:s] ','.join(line[s 1:e].split()) '\n'
csv.write(t)
except ValueError:
csv.write(line)