How to Create a Csv File in Python
Writing CSV files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
Python provides an in-built module called csv
to work with CSV files. There are various classes provided by this module for writing to CSV:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- Using csv.writer class
- Using csv.DictWriter class
Using csv.writer class
csv.writer
class is used to insert data to the CSV file. This class returns a writer object which is responsible for converting the user's data into a delimited string. A csvfile object should be opened with newline=''
otherwise newline characters inside the quoted fields will not be interpreted correctly.
Syntax: csv.writer(csvfile, dialect='excel', **fmtparams)
Parameters:
csvfile: A file object with write() method.
dialect (optional): Name of the dialect to be used.
fmtparams (optional): Formatting parameters that will overwrite those specified in the dialect.
csv.writer
class provides two methods for writing to CSV. They are writerow()
and writerows()
.
- writerow(): This method writes a single row at a time. Field row can be written using this method.
Syntax:
writerow(fields)
- writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.
Syntax:
Writing CSV files in Python writerows(rows)
Example:
import
csv
fields
=
[
'Name'
,
'Branch'
,
'Year'
,
'CGPA'
]
rows
=
[ [
'Nikhil'
,
'COE'
,
'2'
,
'9.0'
],
[
'Sanchit'
,
'COE'
,
'2'
,
'9.1'
],
[
'Aditya'
,
'IT'
,
'2'
,
'9.3'
],
[
'Sagar'
,
'SE'
,
'1'
,
'9.5'
],
[
'Prateek'
,
'MCE'
,
'3'
,
'7.8'
],
[
'Sahil'
,
'EP'
,
'2'
,
'9.1'
]]
filename
=
"university_records.csv"
with
open
(filename,
'w'
) as csvfile:
csvwriter
=
csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
Output:
Using csv.DictWriter class
This class returns a writer object which maps dictionaries onto output rows.
Syntax: csv.DictWriter(csvfile, fieldnames, restval=", extrasaction='raise', dialect='excel', *args, **kwds)
Parameters:
csvfile: A file object with write() method.
fieldnames: A sequence of keys that identify the order in which values in the dictionary should be passed.
restval (optional): Specifies the value to be written if the dictionary is missing a key in fieldnames.
extrasaction (optional): If a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to raise a ValueError will be raised.
dialect (optional): Name of the dialect to be used.
csv.DictWriter provides two methods for writing to CSV. They are:
- writeheader():
writeheader()
method simply writes the first row of your csv file using the pre-specified fieldnames.Syntax:
writeheader()
-
writerows():
writerows
method simply writes all the rows but in each row, it writes only the values(not keys).Syntax:
writerows(mydict)
Example:
import
csv
mydict
=
[{
'branch'
:
'COE'
,
'cgpa'
:
'9.0'
,
'name'
:
'Nikhil'
,
'year'
:
'2'
},
{
'branch'
:
'COE'
,
'cgpa'
:
'9.1'
,
'name'
:
'Sanchit'
,
'year'
:
'2'
},
{
'branch'
:
'IT'
,
'cgpa'
:
'9.3'
,
'name'
:
'Aditya'
,
'year'
:
'2'
},
{
'branch'
:
'SE'
,
'cgpa'
:
'9.5'
,
'name'
:
'Sagar'
,
'year'
:
'1'
},
{
'branch'
:
'MCE'
,
'cgpa'
:
'7.8'
,
'name'
:
'Prateek'
,
'year'
:
'3'
},
{
'branch'
:
'EP'
,
'cgpa'
:
'9.1'
,
'name'
:
'Sahil'
,
'year'
:
'2'
}]
fields
=
[
'name'
,
'branch'
,
'year'
,
'cgpa'
]
filename
=
"university_records.csv"
with
open
(filename,
'w'
) as csvfile:
writer
=
csv.DictWriter(csvfile, fieldnames
=
fields)
writer.writeheader()
writer.writerows(mydict)
Output:
How to Create a Csv File in Python
Source: https://www.geeksforgeeks.org/writing-csv-files-in-python/
0 Response to "How to Create a Csv File in Python"
Post a Comment