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"])
Your code should work for basic data, but some problem may arise in some cases, if you have commas in your data.
The
csvmodule takes care of that problem, as well as any similar problems. The usage is quite easy, you would just do :Note the double parens, we pass a tuple because
writerowsexcept an iterable. Don’t hesitate to check the doc if you want more info.