Python - Parsing A Text File Into A Csv File
I have a text file that is output from a command that I ran with Netmiko to retrieve data from a Cisco WLC of things that are causing interference on our WiFi network. I stripped
Solution 1:
I think your best option is to read all lines of the file, then split into sections starting with AP Name. Then you can work on parsing each section.
Example
s = """AP Name.......................................... 010-HIGH-FL4-AP04
Microwave Oven 11 10 -59 Mon Dec 18 08:21:23 2017
WiMax Mobile 11 0 -84 Fri Dec 15 17:09:45 2017
WiMax Fixed 11 0 -68 Tue Dec 12 09:29:30 2017
AP Name.......................................... 010-2nd-AP04
Microwave Oven 11 10 -61 Sat Dec 16 11:20:36 2017
WiMax Fixed 11 0 -78 Mon Dec 11 12:33:10 2017
AP Name.......................................... 139-FL1-AP03
Microwave Oven 6 18 -51 Fri Dec 15 12:26:56 2017
AP Name.......................................... 010-HIGH-FL3-AP04
Microwave Oven 11 10 -55 Mon Dec 18 07:51:23 2017
WiMax Mobile 11 0 -83 Wed Dec 13 16:16:26 2017"""import re
classAP:
"""
A class holding each section of the parsed file
"""def__init__(self):
self.header = ""
self.content = []
sections = []
section = Nonefor line in s.split('\n'): # Or 'for line in file:'# Starting new sectionif line.startswith('AP Name'):
# If previously had a section, add to listif section isnotNone:
sections.append(section)
section = AP()
section.header = line
else:
if section isnotNone:
section.content.append(line)
sections.append(section) # Add last section outside of loopfor section in sections:
ap_name = section.header.lstrip("AP Name.") # lstrip takes all the characters given, not a literal stringfor line in section.content:
print(ap_name + ",", end="")
# You can extract the date separately, if needed# Splitting on more than one space using a regex
line = ",".join(re.split(r'\s\s+', line))
print(line.rstrip(',')) # Remove trailing comma from imperfect split
Output
010-HIGH-FL4-AP04,MicrowaveOven,11,10,-59,MonDec1808:21:232017010-HIGH-FL4-AP04,WiMaxMobile,11,0,-84,FriDec1517:09:452017010-HIGH-FL4-AP04,WiMaxFixed,11,0,-68,TueDec1209:29:302017010-2nd-AP04,MicrowaveOven,11,10,-61,SatDec1611:20:362017010-2nd-AP04,WiMaxFixed,11,0,-78,MonDec1112:33:102017139-FL1-AP03,MicrowaveOven,6,18,-51,FriDec1512:26:562017010-HIGH-FL3-AP04,MicrowaveOven,11,10,-55,MonDec1807:51:232017010-HIGH-FL3-AP04,WiMaxMobile,11,0,-83,WedDec1316:16:262017
Tip:
You don't need Python to write the CSV, you can output to a file using the command line
python script.py > output.csv
Post a Comment for "Python - Parsing A Text File Into A Csv File"