Difference between writerow() and writerows() methods of Python csv module
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.
Related videos on Youtube
Turzo
Updated on November 10, 2021Comments
-
Turzo about 1 yearI 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
csvmodule with very similar names -writerow()andwriterows(). 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 almost 2 yearsIs there any performance comparison b/w the two methods? -
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 over 1 yearWhile your post answers the question, consider adding some code examples for the same.