I'm trying to write a Python script to extract the Wi-Fi data from txt file to csv
Here is the txt data:
Wed Oct 7 09:00:01 UTC 2020
BSS 02:ca:fe:ca:ca:40(on ap0_1)
freq: 2422
capability: IBSS (0x0012)
signal: -60.00 dBm
primary channel: 3
last seen: 30 ms ago
BSS ac:86:74:0a:73:a8(on ap0_1)
TSF: 229102338752 usec (2d, 15:38:22)
freq: 2422
capability: ESS (0x0421)
signal: -62.00 dBm
primary channel: 3
I need to extract the txt data to csv file in this format:
Time | BSS | freq |capability |signal| primary channel |
----------------------------+---------------------------+------+-------------+------+-----------------+
Wed Oct 7 09:00:01 UTC 2020|02:ca:fe:ca:ca:40(on ap0_1)| 2422 |IBSS (0x0012)|-60.00| 3 |
|ac:86:74:0a:73:a8(on ap0_1)| 2422 |IBSS (0x0012)|-62.00| 3 |
This is my unfinished code:
import csv
import re
fieldnames = ['TIME', 'BSS', 'FREQ','CAPABILITY', 'SIGNAL', 'CHANNEL']
re_fields = re.compile(r'({})+:\s(.*)'.format('|'.join(fieldnames)), re.I)
with open('ap0_1.txt') as f_input, open('ap0_1.csv', 'w', newline='') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames= fieldnames)
csv_output.writeheader()
start = False
for line in f_input:
line = line.strip()
if len(line):
if 'BSS' in line:
if start:
start = False
block.append(line)
text_block = '\n'.join(block)
for field, value in re_fields.findall(text_block):
entry[field.upper()] = value
if line[0] == 'on ap0_1':
entry['BSS'] = block[0]
csv_output.writerow(entry)
else:
start = True
entry = {}
block = [line]
elif start:
block.append(line)
When I run it, the data isn't placed correctly.
Please let me know how to fix this. I'm just a beginner in programming and would appreciate any advice. Thank you.
