Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

csv

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?

like image 702
Turzo Avatar asked Oct 12 '15 23:10

Turzo


People also ask

What is Writerow in csv?

writer() function is used to create a writer object. The writer. writerow() function is then used to write single rows to the CSV file.

Is Writerows a function of csv module?

csv file. The writerow method writes a row of data into the specified file. It is possible to write all data in one shot. The writerows method writes all given rows to the CSV file.

What are the two different ways to import csv module?

Answer: On the Data tab, in the Get & Transform Data group, click From Text/CSV. In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import. In the preview dialog box, you have several options: Select Load if you want to load the data directly to a new worksheet.


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

like image 104
horns Avatar answered Oct 17 '22 01:10

horns