0

Maybe it's not clear enough, let me explain : I want to write into a csv file, i'm using a list with 3 strings in it for example and i want to give every elements of the list to writer.writerow() as write.writerow(['test', 'test1', 'test2']).

I cannot give directly the list otherwise it will print " ['test1', 'test2', 'test3'] " in only one cell of the csv file.

I was thinking about a for loop maybe, but i'm not a beast with python so any help would be appreciated.

Couldn't find any help on the internet.

N.Quentin
  • 13
  • 3
  • 2
    I'm not 100% sure, but maybe what you're after is `writer.writerow(*your_list)`, where `*` unpacks the list? – Peter Nov 18 '16 at 15:24
  • Possible duplicate of [Python: expand list to function arguments](http://stackoverflow.com/questions/7745952/python-expand-list-to-function-arguments) – n00dl3 Nov 18 '16 at 15:25
  • it says Python versions < 3.5 do not support `*` in tuples, lists and sets :/ – N.Quentin Nov 18 '16 at 15:26
  • are you looking for https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows – danidee Nov 18 '16 at 15:27
  • If you are using [csv.writer](https://docs.python.org/3.7/library/csv.html#csv.writer), it looks like you are doing it right. It should print the strings in separate columns. – eigil Nov 18 '16 at 15:27

2 Answers2

2

I guess this will help you.

import re

test = "['test1', 'test2', 'test3']"
match = re.compile(r"'\w+'")
my_list = [t.strip("'") for t in match.findall(test)]
for line in my_list:
    writer.writerow(line)
RChanger
  • 110
  • 3
0

From the CSV docs, it looks like anything passed to .writerow() that isn't a string (eg., your list) is stringified.

Try this?

mylist = ['test', 'test1', 'test2']
for line in mylist:
    writer.writerow(line)
Danielle M.
  • 3,607
  • 1
  • 14
  • 31
  • It doesn't help because it prints every word on a new line, thanks anyway – N.Quentin Nov 18 '16 at 15:40
  • Oh, I thought that's what you wanted to do. Can you give an example, using the `['test', 'test1', 'test2']` list, of what you'd like the output to be? Do you want `test, test1, test2` in one line? – Danielle M. Nov 18 '16 at 16:03