简体   繁体   中英

How do you write a quoted, comma separated list of items to CSV file without the last comma in quoted list?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM