jab
jab

Reputation: 5823

csv writer ignore certain values

Let's say that I want the built in python csv writer to ignore certain string values in array (place no value between commas in output). For instance,

my_list = [4, 'foo', 'close', 9, 0]

csv output => 4, ,'close', 9, 0

I would provide a parameter 'foo' that would designate to be ignored by the writer, is this possible? If so, could somebody help on the implementation?

Upvotes: 1

Views: 830

Answers (4)

Lanaru
Lanaru

Reputation: 9721

You could try this:

ignored_strings = {'foo', 'ignored2', 'ignored3'}

my_list_filtered = [value if value not in ignored_strings else '' for value in my_list]

That replaces each value you want to ignore by an empty string. You can then use the csv writer to print out the new list.

You could also simply remove values you don't want from a list using an 'if' statement at the end of the list comprehension, depending on what you want your output to look like.

Upvotes: 0

jamylak
jamylak

Reputation: 133634

>>> import csv
>>> my_list = [4, 'foo', 'close', 9, 0]
>>> with open('test.csv', 'w') as fout:
        w = csv.writer(fout, delimiter=',')
        w.writerow([x if x != 'foo' else ' ' for x in my_list])

>>> print open('test.csv').read()
4, ,close,9,0

Upvotes: 1

codebox
codebox

Reputation: 20254

You could use something like this to do replacements within the list:

map(lambda x : str(x) if x != 'foo' else ' ', my_list)

and just do a join to create the output string:

','.join(map(lambda x : str(x) if x != 'foo' else ' ', my_list))

Upvotes: 0

David Robinson
David Robinson

Reputation: 78620

You could do something like this, if you have a 2D list of rows to write:

lines = [[4, 'foo', 'close', 9, 0], [5, 'foo', 'close', 9, 0]]

import csv
with open("outfile.csv", "wb") as outf:
    w = csv.writer(outf)
    for line in lines:
        w.writerow(["" if e == "foo" else e for e in line])

Upvotes: 2

Related Questions