Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python csv.writer without filehandler

Tags:

python

csv

csv.writer requires me to feed in a real csv file. is there a way I can feed it a string or a list to write to instead of an actual file? I want to return the csv for another function without writing a file.

hold = [some_list]
blank = []
   w = csv.writer(blank, delimiter=',')
   w.writerows(hold)
   return w

Traceback (most recent call last):
    w = csv.writer(blank, delimiter=',')
    TypeError: argument 1 must have a "write" method
like image 484
D3l_Gato Avatar asked Mar 11 '23 07:03

D3l_Gato


1 Answers

A StringIO object is suitable for this:

>>> f = StringIO()
>>> w = csv.writer(f)
>>> w.writerow(['hello', 'world'])
13
>>> f.getvalue()
'hello,world\r\n'
like image 101
wim Avatar answered Mar 20 '23 07:03

wim