Reputation: 125
I have a CSV file which has three columns. The third column "row[02]" has a listing of IP's which contains a list of IP's that are comma delimited. I would like to turn the following:
"column01", "column02", "192.168.1.1, 192.168.2.1, 192.168.3.1"
into (minus the bullets):
- column01, column02, 192.168.1.1
- column01, column02, 192.168.2.1
- column01, column02, 192.168.3.1
Provided is my code, but the output keeps displaying the following:
row01, row02, 192.168.1.1, 192.168.2.1, 192.168.3.1
Please let me know if any other information is needed. Thanks in advance.
Original Code:
#!/usr/bin/python
import csv, sys, time, logging
s = time.strftime('%Y%m%d%H%M%S')
# Create exception file from standard output
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open((s) + "_" + sys.argv[1], "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def main():
# Start screen capture to output into CSV file
sys.stdout = Logger()
# File input argument
with open(sys.argv[1], "rb") as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print row[0], ",", row[1], ",", row[2]
if __name__=='__main__':
main()
Updated Code:
#!/usr/bin/python
import csv, sys, time, logging
s = time.strftime('%Y%m%d%H%M%S')
# Create exception file from standard output
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open((s) + "_" + sys.argv[1], "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def main():
# Start screen capture to output file
sys.stdout = Logger()
# File input argument
with open(sys.argv[1], "rb") as f:
reader = csv.reader(f, delimiter=',', skipinitialspace=True)
for row in reader:
network = row[0].replace(" ","")
network_group = row[1].replace(" ","")
address = row[2].replace(',','\n').replace(" ","")
if "-" in address: #parse network ranges
try:
print IP(address), network, network_group
except:
netrange = address.replace('-'," ").replace(" ",",")
print netrange, ",", network, ",", network_group
else:
print address, ",", network, ",", network_group
if __name__=='__main__':
main()
Upvotes: 0
Views: 1082
Reputation: 365737
The reason it's printing this:
row01, row02, 192.168.1.1, 192.168.2.1, 192.168.3.1
Is that you asked it to do exactly that for each row:
for row in reader:
print row[0], ",", row[1], ",", row[2]
If you want it to do something different, you have to tell it to do something different. It can't read your mind. So, if you want to, e.g., split row[2]
on commas, you need to write some code that does that. Like this:
for row in reader:
addresses = row[2].split(", ")
for address in addresses:
print row[0], ",", row[1], ",", address
Upvotes: 4