I think you might want to have a look at your three lists, and at zip
.
If the lists are not of the same length, then zip will toss the offending ones out.
#!/usr/bin/env python
import csv
import codecs
L1 = ["foo", "bar", "bat", "baz"] # <-- this guy has one more! expect to be truncated
L2 = ["hoo", "hah", "hee"] # <--note, one field less!
L3 = range(2) #<--note, only two fields long! expect entire line to be dropped!
with codecs.open("test.csv", "w", encoding="utf-8") as f:
writer = csv.writer(f, lineterminator="\n", delimiter=";")
for row in zip(L1, L2, L3):
writer.writerow(row)
Since you only have two values in L3, and the rest have three, zip will truncate your bad output.
~$ cat test.csv
foo;hoo;0
bar;hah;1
You will, of course, notice that I'm using zip to put out a single list value for each index in the three lists. This differs from your example. I don't know exactly what you are doing there, but if each of those "l" values represents a list, there is no real need to explicitly create those values, then add them to a list later.
Again, it would be nice to see an example of your inputs (if possible). One might have to insert None
values (or empty strings, or whatever) when building those lists to get them to "match up".
L1 = ["foo", "bar", "bat", "baz"]
L2 = ["hoo", "hah", "hee", None]
L3 = range(2) + [None, None]
Which will probably give you what you want:
~$ cat test.csv
foo;hoo;0
bar;hah;1
bat;hee;
baz;;