Updated May 23, 2023
Introduction to Python write CSV file.
Python programming language allows the developer to access a CSV file where a developer can execute actions like read and write a file. CSV Library is responsible for allowing developers to execute these actions. When we have to deal with file input-output functions, specifically CSV files, python provides the CSV libraries, which hold a number of functions to work with the file.
Syntax:
Given below is the syntax of Python writes CSV file:
csv.writer(csvfile, dialect='excel', **fmtparams)
The syntax starts with the csv keyword followed by the function writer, which is responsible for opening the file and writing it. Now before writing, we read the file and define our needs. The mentioned syntax will read the file that we pass in, which is important prior to reading or writing the file.
Parameters:
- csvfile is the object, which is the file that we want to operate on.
- The dialect is an optional parameter, which defines that we want an excel generated csv file.
- We can have different types of files. Finally, the fmtparams is a formatting parameter that is responsible for overriding the specification maintained by the dialect in need.
How to write CSV file in Python using Various Methods?
We will demonstrate the working of the csv function within Python using the Python CSV library.
Example #1
Our first example is a code that will open a CSV file and write a few lines.
Code:
import csv
with open('start.csv', 'w') as csvfile:
startwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
startwriter.writerow(['Start'] * 2 + ['working example of csv write'])
startwriter.writerow(['starting', 'this is an example', 'just a simple working example'])
Explanation:
- I started with importing the csv library for Python, then opened the function to access the start.csv file. If in case the file does not exist, the code will create a new file with mentioned name and type.
- Then we have startwriter, where we access the file with write permissions and pass the filename along with other parameters.
- Next, we have our first statement, which will write Start two times, followed by the next sentence.
- Finally, the last statement is as we have passed with the only difference where it added this | symbol.
Upon successful compilation and execution, the output that must be written into a csv file must be like this:
Start |working example of csv write|
starting |this is an example| |just a simple working example|
Output:
Just as we expected, the statements have been printed in a csv file.
Example #2
Moving on, we will implement the csv.writer function from the csv library here and write three lines of quotes to a csv file. We will open an empty csv file, then write the data.
Code:
import csv
row_list = [
["SN", "Name", "Quotes"],
[1, "Linus Torvalds", "Talk is cheap. Show me the code."],
[2, "Martin Fowler", "Any fool can write code that a computer can understand. Good programmers write code that humans can understand."],
[3, "Anonymous", "The most important property of a program is whether it accomplishes the intention of its user."]
]
with open('quotes.csv', 'w') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
Explanation:
- Like other examples, we begin this one by importing the CSV library. Then we have defined our data set for input which is in rows format. Then we have our data that is to be written within the empty csv file.
- Then we have an open function, where we have passed the csv file with ‘w’ right, meaning writable, as a file. Then we have our writer, which holds the file with the important parameters. Finally, we have the writerows function, which will write the list of rows that we have passed into the writer file. The output of the program will be a csv file with names as quotes, with those quotes written into it.
Output:
Example #3
Code:
import csv
newdict =[{'branch': 'ME', 'cgpa': '9.4', 'student_name': 'Sulaksh', 'year': '2'},
{'branch': 'COE', 'cgpa': '8.9', 'student_name': 'Amit', 'year': '2'},
{'branch': 'IF', 'cgpa': '8.3', 'student_name': 'Rutuja', 'year': '2'},
{'branch': 'IM', 'cgpa': '7.1', 'student_name': 'Madhu', 'year': '2'}]
fields = ['student_name', 'branch', 'year', 'cgpa']
filename = "uni_records.csv"
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fields)
writer.writeheader()
writer.writerows(newdict)
Explanation:
- We started by importing the csv module. Next, we created a dictionary data type and added a set of sentences to it. Then, we defined the header for our CSV file, which is named fields and contains four column names. After that, we specified the name of the file and accessed it using the open function.
- We pass the filename as csvfile and the fields as fieldnames. Our code then uses the writer to write the header of the file. After that, the data from our dictionary is written to the file.
- Once the code is executed successfully, a CSV file named uni_records.csv will be generated. This file will contain the data that we provided in the dictionary.
Output:
As expected, our code has been executed, and a new csv file has been created with the data we intended to have. All our examples have successfully worked as intended. There are multiple ways and methods to implement the writer function for csv, and as per our needs for the project, we can implement it.
Conclusion
CSV writer is a well-used function of the CSV library of Python. The csv library allows us to access and operate multiple operations over a csv file, and the writer is one of them. We simply access the file and write down the intended data in the file. In case the file doesn’t exist, it will be created.
Recommended Articles
We hope that this EDUCBA information on “Python write CSV file” was beneficial to you. You can view EDUCBA’s recommended articles for more information.