In the previous post, we learnt about reading a CSV file in Python. Now in this post, we will learn how to write data into CSV using python's inbuilt writer object.
Writing data to CSV files is very easy and convenient. In Python to write a data or any delimited text to CSV is possible using an inbuilt module name CSV. It has a Writer class i.e. "csv.writer" that returns a writer object.
This writer object has two methods one helps to write one row at a time and another method helps to insert multiple rows at a time.
In this post we will see writing CSV files using both the methods:
Writing CSV File Using writerow() Method
def write_csv():header = ["id", "language", "company"]
row1 = ["1", "Python", "Development"]
row2 = ["2", "HTML", "Testing"]
row3 = ["3", "Java", "Coding"]
with open('sample_csv1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(header)
writer.writerow(row1)
writer.writerow(row2)
#main function
def main():
write_csv()
Writing CSV File Using writerows() Method
def write_multiple_rows_csv():
header = ["id", "language", "company"]
rows = [["1", "Python", "Development"],
["2", "HTML", "Testing"],
["3", "Java", "Coding"]]
with open('sample_csv1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(header)
writer.writerows(rows)
#main function
def main():
write_multiple_rows_csv()