Reputation: 337
What is an elegant, Pythonic way to write lines of data that contain an embedded (quoted) list of comma separated values to a CSV file?
I need to put quotes around a comma separated list so that Excel doesn't break the list into separate columns when looking at it with Excel.
My function looks like this:
def write_customer_list(self):
with open('reports/systems.csv', 'w') as f:
f.write('Systems Report for week {}\n'.format(self.week))
f.write('CustId,IP_AddrList,ModelNum\n') # Header for csv file
for cust_id, system in self.systems.items():
f.write('{}'.format(cust_id))
f.write(',\"') # open double quote string for list
for value in system['ip_addr_list']:
f.write('{},'.format(value))
f.write('\"') # close the quote
f.write(',{}\n'.format(system['model_num']))
Output looks like this:
123,"10.1.1.6,10.1.2.12,10.1.3.15,",NEX3601
124,"10.2.5.6,10.2.1.12,",NEX3604
How do I get rid of the trailing ',' in the ip list?
Upvotes: 0
Views: 330
Reputation: 9529
Instead of
for value in system['ip_addr_list']:
f.write('{},'.format(value))
do
f.write( ','.join(system['ip_addr_list']) )
This will give you a comma separated list that does not have a comma at the end. See the documentation of the join function for more info.
You may also want to take a look at the CSV module. When using this module you only need to provide your list of data, and it will take care of formatting everything for you.
Upvotes: 1