简体   繁体   English

您如何将带引号,逗号分隔的项目列表写入CSV文件,而引号列表中没有最后一个逗号?

[英]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? 用一种优雅的Python方式将包含嵌入的(用引号引起来的)逗号分隔值列表的数据行写入CSV文件?

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. 我需要将引号括在逗号分隔的列表周围,以便在使用Excel查看时,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? 如何摆脱IP列表中尾部的','?

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. 有关更多信息,请参见join函数的文档。

You may also want to take a look at the CSV module. 您可能还想看看CSV模块。 When using this module you only need to provide your list of data, and it will take care of formatting everything for you. 使用此模块时,您只需要提供数据列表,它将为您格式化所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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