Pass list of different named tuples to different csv by tuple name <p>I have a program in which I wish to record all major changes that occur. For example: each time a variable x changes in value record the time of the change and the change itself. Within the program there are many such changes and not all have the same number of parameters. </p> <p>I decided to use namedtuples to store each instance of a change and to then put those namedtuples into a single master data list -ready for export to csv. I have used tuples as of course they are immutable which is ideal for record keeping. Below I have tried to explain in as concise a manner as possible what I have done and tried. Hopefully my problem and attempts so far are clear.</p> <p>So I have:</p> <pre><code>data = [] </code></pre> <p>as the main repository, with namedtuples of the form:</p> <pre><code>a_tuple = namedtuple('x_change', ['Time', 'Change']) another_tuple = namedtuple('y_change', ['Time', 'Change', 'id']) </code></pre> <p>I can then append instances of these namedtuples each time a change is detected to data using commands as below:</p> <pre><code>data.append(a_tuple(a_time, a_change)) data.append(another_tuple(a_time, a_change, an_id)) </code></pre> <p>If I then print out the contents of data I would get output like:</p> <pre><code>x_change(a_time=4, a_change=1) y_change(a_time=5, a_change=3, an_id = 2) y_change(a_time=7, a_change=1, an_id = 3) x_change(a_time=8, a_change=3) </code></pre> <p>what I would like to do is export these tuples to csv files by tuple name. So in the above case I would end up with two csv files of the form:</p> <pre><code>name, time, change x_change, 4, 1 x_change, 8, 3 </code></pre> <p>and;</p> <pre><code>name, time, change, id y_change, 5, 3, 2 y_change, 7, 1, 3 </code></pre> <p>I have to date managed to write to a single csv as below:</p> <pre><code>with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(row) </code></pre> <p>which produces the output minus the tuple name. So:</p> <pre><code>4, 1 5, 3, 2 7, 1, 3 8, 3 </code></pre> <p>I have also tried:</p> <pre><code>with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(str(row)) </code></pre> <p>Which splits the file into csv format, including the tuple name, by every character getting (first line only included): </p> <pre><code>x, _, c, h, a, n, g, e, 4, 1 </code></pre> <p>I have searched for a solution but not come across anything that fits what I am trying to do and am now at a loss. Any assistance would be appreciated.</p>