【发布时间】:2018-12-06 00:46:00
【问题描述】:
将包含逗号分隔值的嵌入式(引用)列表的数据行写入 CSV 文件的优雅、Pythonic 方式是什么?
我需要在逗号分隔的列表周围加上引号,以便 Excel 在使用 Excel 查看列表时不会将列表分成单独的列。
我的函数如下所示:
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']))
输出如下所示:
123,"10.1.1.6,10.1.2.12,10.1.3.15,",NEX3601
124,"10.2.5.6,10.2.1.12,",NEX3604
如何去掉 ip 列表中的尾随 ','?
【问题讨论】:
-
f.write('{}'.format(cust_id))为什么不只是f.write(cust_id)? -
CSV 编写器需要一个表示单行的列表(或某种可迭代的)。 不要使用
format(),只需将列表传递给作者即可。您应该使用 CSV 模块。
标签: python