python写入csv文件中添加行_在python中为csv文件输出键添加值
這是我的輸入csv文件。
client_ip listener_service listener_port
127.0.0.1 LMNO 123
::1 PQAR 768
::1 PQAR 128
12.4.5.2.4 67
我想要的輸出如下
client_ip listener_service listener_port
127.0.0.1 LMNO 123
::1 PQAR 768,128
12.4.5.2.4 67
with open('client.csv', 'r') as fin, open('client_out_file.csv', 'w',newline='') as ffout:
reader = csv.reader(fin)
writer = csv.writer(ffout)
d = {} # Empty Dictionary
for row in reader:
nkey = row[0]+row[1] #Creating Key using combinations
if nkey not in d:
d[nkey] = row #Assiging Value to the key
writer.writerow(row)
else:
#print(row[2])
#d[nkey]=d[nkey]+list(row[2])
#writer.writerow(row)
需要幫助
其他的
部分或更簡單的解決方案,以便在不替換以前的值的情況下,如果出現(xiàn)鍵的任何新值,它將被包括在內(nèi)。我試圖避免將csv內(nèi)容保存在列表中,然后使用字典-這需要額外的行。僅供參考-我有大的csv文件。
總結(jié)
以上是生活随笔為你收集整理的python写入csv文件中添加行_在python中为csv文件输出键添加值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Circling Round Treas
- 下一篇: 跳出坑爹的 Runtime Librar
