0

In my python application I needed to export some values as csv. But the problem is that I need to "prepend" some values to it. I tried the following solution:

import csv
from datetime import datetime
from collections import deque

def writeCSV(path,participants,values):

    time=datetime.now()

    with open(path, 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for value in values:
            if type(value) is list:
                value.prepend(participants)
                value.prepend(time)
                writer.writerow(value)
            else:
                writer.writerow([time,participants,value])


if __name__ == '__main__':
    writeCSV('demo.csv',15,[['hentai','ecchi'],['power','ranger']])

But I get the follwing error:

Traceback (most recent call last):
  File "csv_deque.py", line 21, in <module>
    writeCSV('demo.csv',15,[['hentai','ecchi'],['power','ranger']])
  File "csv_deque.py", line 13, in writeCSV
    value.prepend(participants)

How I can fix that.

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164

1 Answers1

0

The problem is that list has no prepend method. (But would be nice if had)

So as in my case I had similar problem: I needed to prepend a number of participants and the datetime to each entry of a csv file.

So, as I did in my case, I would suggest your script to turn into like this:

import csv
from datetime import datetime
from collections import deque

def writeCSV(path,participants,values):

    time=datetime.now()

    with open(path, 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for value in values:
            if type(value) is list:
                value=deque(value)
                value.appendleft(participants)
                value.appendleft(time)
                writer.writerow(value)
            else:
                writer.writerow([time,participants,value])


if __name__ == '__main__':
    writeCSV('demo.csv',15,[['hentai','ecchi'],['power','ranger']])

As you can see I use dequeue as seen in this answer. Also you can see you can write a dequeue object as csv as well.

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164