Difference between writerow() and writerows() methods of Python csv module

45,547

Solution 1

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

Solution 2

writerows(seq) is equivalent to:

for item in seq:
    writerow(item)

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

Solution 3

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.

Share:
45,547

Related videos on Youtube

Turzo
Author by

Turzo

Updated on November 10, 2021

Comments

  • Turzo
    Turzo about 1 year

    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?

  • TheSohan
    TheSohan almost 2 years
    Is there any performance comparison b/w the two methods?
  • horns
    horns almost 2 years
    @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
  • nobleknight
    nobleknight over 1 year
    While your post answers the question, consider adding some code examples for the same.

Related