19

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?

3 Answers 3

27

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).

2
  • 2
    Is there any performance comparison b/w the two methods?
    – TheSohan
    Feb 2, 2021 at 6:46
  • 2
    @TheSohan I have not done a comparison, but if I had to guess I would put my money on writerows if you already have multiple rows in an iterable
    – horns
    Feb 5, 2021 at 16:36
7

writerows(seq) is equivalent to:

for item in seq:
    writerow(item)

So the only difference is that writerows lets you pass multiple values!

1
  • It is not true. Method .writerows is about 6% faster than .writerow (based on 1 mln lines benchmarks). Nov 26, 2022 at 17:33
4

The technical difference is that writerow is going to write a list of values into a single row whereas writerows is going to write multiple rows from a buffer that contains one or more lists.

The practical difference is that writerows is going to be faster, especially if you have a large number of writes to perform, because it can carry them out all at once.

1
  • While your post answers the question, consider adding some code examples for the same. Jun 8, 2021 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.