Answer a question

I am new to the realm of Python. I've been playing with some I/O operations on CSV files lately, and I found two methods in the csv module with very similar names - writerow() and writerows(). The difference wasn't very clear to me from the documentation. I tried searching for some examples but they seem to have used them almost interchangeably.

Could anyone help clarify a little bit?

Answers

writerow takes an iterable of cells to write:

writerow(["foo", "bar", "spam"])
->
foo,bar,spam

writerows takes an iterable of iterables of cells to write:

writerows([["foo", "bar", "spam"],
           ["oof", "rab", "maps"],
           ["writerow", "isn't", "writerows"]])
->
foo,bar,spam
oof,rab,maps,
writerow,isn't,writerows

So writerow takes 1-dimensional data (one row), and writerows takes 2-dimensional data (multiple rows).

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐