0

Possible Duplicate:
python csv: save results to csv file
Python: How to write a dictionary of tuple values to a csv file?

Previously I use this to write the results line by line to a text file, in each line, values are separated by tab

fd_out.write("%s\t%d\t%d\t%s\n" % (obj["name"],obj["count"],obj["age"],obj["params"]["country"])

but now I want to have CSV output instead, how am I suppose to write the code? Just like this or should I import CSV and use some other method? Sorry, I am quite a newbie of programming...

fd_out.write("%s,%d,%d,%s\n" % (obj["name"],obj["count"],obj["age"],obj["params"]["country"])
Community
  • 1
  • 1
manxing
  • 3,165
  • 12
  • 45
  • 56

2 Answers2

6

Your code should work for basic data, but some problem may arise in some cases, if you have commas in your data.

The csv module takes care of that problem, as well as any similar problems. The usage is quite easy, you would just do :

writer = csv.writer(fd_out)
writer.writerows((obj["name"],obj["count"],obj["age"],obj["params"]["country"]))

Note the double parens, we pass a tuple because writerows except an iterable. Don't hesitate to check the doc if you want more info.

madjar
  • 12,691
  • 2
  • 44
  • 52
1

"CSV" is not a standard, and even though "CSV" literally means "comma-separated values", using tab as the delimiter is just as common as a comma, if not more common. See also wikipedia: http://en.wikipedia.org/wiki/Comma-separated_values

To cater for CSV fields containing the delimiter (i.e. tab or comma), it's common to quote the data, i.e. with double quotes. There is no standard - sometimes only data fields that contains the delimiter is quoted. In the example below all fields will be quoted.

With the csv built-in library it's quite easy to modify the format of the output CSV file as you like.

import csv

objs = [{'name': 'knut', 'age': 74, 'count': 13},
        {'name': 'lydia', 'age': 14, 'count': 3}]

with open("/tmp/example.csv", "w") as outfile:
    ## Ordering of the fields in the CSV output
    headers = ['name', 'age', 'count']

    ## although "CSV" stands for "comma separated values", 
    ## it's quite common to use other delimiters i.e. TAB
    ## and still call it "CSV".
    writer = csv.writer(outfile, delimiter="\t", quotechar='"', quoting=csv.QUOTE_ALL)

    ## it's common in CSV to have the headers on the first line
    writer.writerow(headers)

    ## Write out the data
    for obj in objs:
        writer.writerow([obj[key] for key in headers])

This example also demonstrates condensed list operations in python ... [obj[key] for key in headers] means "give me the list of obj[key] for all keys in header".

tobixen
  • 3,893
  • 1
  • 20
  • 20