Write CSV file using Python with the help of a csv dictionary / nested csv dictionary

2024/9/20 10:38:21

I am having a csv file and i want to write it to another csv file. It's a bit complicated than it seems. Hoping someone to correct my code and rewrite it, so that i can get the desired csvfile. I am using both versions python 2 and 3.

mycsvfile:id,field1,point_x,point_y,point_z
a1,x1,10,12,3
b1,x2,20,22,5
a2,x1,25,17,7
a1,x2,35,13,3
a1,x5,15,19,9
b1,x1,65,11,2
b2,x5,50,23,1
b2,x1,75,17,7
c1,x2,70,87,2
c2,x1,80,67,4
c3,x2,85,51,6

Figure: mycsvfile

Mycode:

import os
import csv
import collections
from csv import DictWriter    with open(r'C:\Users\Desktop\kar_csv_test\workfiles\incsv.csv', 'r') as csvfile:reader = csv.reader(csvfile, delimiter=',')my_dict = collections.defaultdict(dict)for row in reader:my_dict[row[0]][row[1]] = [row[2],row[3],row[4]]print (my_dict)with open(r'C:\Users\Desktop\kar_csv_test\workfiles\outcsv.csv','w', newline='') as wf:fieldnames = ['id', 'x1(point_x)', 'x1(point_y)', 'x1(point_z)', 'x2(point_x)', 'x2(point_y)', 'x2(point_z)'] # >>>>>>etc, till x20(point_x), x20(point_y), x20(point_z)my_write = csv.DictWriter(wf, fieldnames = fieldnames, delimiter = ',')my_write.writeheader()Desired output as csv file:id,x1(point_x),x1(point_y),x1(point_z),x2(point_x),x2(point_y),x2(point_z)       
a1,10,12,3,35,13,3,
a2,25,17,7,,,,
b1,65,11,2,20,22,5,
b2,75,17,7,,,,
c1,,,,70,87,2,
c2,80,67,4,,,,
c3,,,,85,51,6,

Figure: Desiredcsvfile

Answer

This answer is for Python3 only. The csv module has a very different interface between Python2 and Python3 and writing compatible code is beyond what I am ready to do here.

Here, I would compute the fieldnames list, and compute each row on the same pattern:

...
with open(r'C:\Users\Desktop\kar_csv_test\workfiles\outcsv.csv','w', newline='') as wf:fieldnames = ['id'] + ['x{}(point_{})'.format(i, j)for i in range(1, 6) for j in "xyz"] # only up to x5 heremy_write = csv.DictWriter(wf, fieldnames = fieldnames, delimiter = ',')my_write.writeheader()for k, v in my_dict.items():row = {'x{}(point_{})'.format(i, k):v.get('x{}'.format(i), ('','',''))[j]   # get allows to get a blank triple is absentfor i in range(1,6) for j,k in enumerate("xyz")}row['id'] = k                                  # do not forget the id...my_write.writerow(row)

With your example data, it gives:

id,x1(point_x),x1(point_y),x1(point_z),x2(point_x),x2(point_y),x2(point_z),x3(point_x),x3(point_y),x3(point_z),x4(point_x),x4(point_y),x4(point_z),x5(point_x),x5(point_y),x5(point_z)
a1,10,12,3,35,13,3,,,,,,,15,19,9
b1,65,11,2,20,22,5,,,,,,,,,
a2,25,17,7,,,,,,,,,,,,
b2,75,17,7,,,,,,,,,,50,23,1
c1,,,,70,87,2,,,,,,,,,
c2,80,67,4,,,,,,,,,,,,
c3,,,,85,51,6,,,,,,,,,
https://en.xdnf.cn/q/119375.html

Related Q&A

saving data to txt file using python

I am new in python, and I really need some help. I am doing this memory game where I need to save user, game score and time into a text file using python. I have tried several ways to do it, but nothin…

How can I create bounding boxes/contour around the outer object only - Python OpenCV

So Ive been trying to make bounding boxes around a couple of fruits that I made in paint. Im a total beginner to opencv so I watched a couple tutorials and the code that I typed made, makes contours ar…

resuming download file ftp python3.*

There is a file (1-7Gb) that you need to pick up. The network periodically falls, so it is necessary to implement the method of resume. For example, in 1 communication session downloaded 20% the networ…

printing files based on character

I have a directory(data) that contain thousand of files.Each time I want to select three files that are just differ by only one characterAB[C,D,E] and want to perform some computation on the selected t…

Parsing CSV file using Panda

I have been using matplotlib for quite some time now and it is great however, I want to switch to panda and my first attempt at it didnt go so well.My data set looks like this:sam,123,184,2.6,543 winte…

Getting division by zero error with Python and OpenCV

I am using this code to remove the lines from the following image:I dont know the reason, but it gives me as output ZeroDivisionError: division by zero error on line 34 - x0, x1, y0, y1 = (0, im_wb.sha…

Pandas complex calculation based on other columns

I have successfully created new columns based on arithmetic for other columns but now I have a more challenging need to first select elements based on matches of multiple columns then perform math and …

how to generate word from a to z [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

How to webscrape all shoes on nike page using python

I am trying to webscrape all the shoes on https://www.nike.com/w/mens-shoes-nik1zy7ok. How do I scrape all the shoes including the shoes that load as you scroll down the page? The exact information I …

Pyo in Python: name Server not defined

I recently installed Pyo, and I entered Python 3.6 and typedfrom pyo import * s = Server().boot() s.start() sf = SfPlayer("C:\Users\myname\Downloads\wot.mp3", speed=1, loop=True).out()but I …