How to write and read CSV files in Python
Being a famous and handy programming language, python allows you to do lots of different tasks, including reading and writing CSV files.
Prerequisites
- You must have installed python on your device.
- You may need some python knowledge.
Writing a CSV file
- Import the CSV module.
- Open the file and create a CSV writer with the proper arguments
- The first one is the file.
- The delimiter can be whatever character you want.
- The quotechar optional parameter tells the writer which characters to use to quote fields when writing. Whether quoting is used or not, however, is determined by the quoting optional parameter.
- The quoting parameter. If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote fields only if they contain the delimiter or the quotechar. This is the default case. If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all fields. If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields containing text data and convert all numeric fields to the float data type. If quoting is set to csv.QUOTE_NONE, then .writerow() will escape delimiters instead of quoting them. In this case, you also must provide a value for the escapechar optional parameter.
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Reading a CSV file
- Import the CSV module.
- Open the CSV file.
- Create an object reader, and iterate over the rows:
import csv
with open('eggs.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader: print(', '.join(row))
any more questions about python? check out our forum!