Reading and writing csv files in Python
Python includes functionality in the form of modules.There is a library which is included as part of Python.If other features are required then there are extra libraries which can be downloaded.To work with CSV files in Python there is a CSV module.Using the csv module we can read and write csv files.
Reading CSV files
To read the contents of CSV file we can use the DictReader method of the csv module.We pass the file object and delimiter as arguments.Though delimiter is optional argument and is not required.We can specify any delimiter we want to use while reading the file depending on the file delimiter.
In the following example we are reading the contents of the csv file called csvSample.csv and printing the values of the different rows and columns:
with open('csvSample.csv') as f:
csv_values = csv.DictReader(f)
for row in csv_values:
if required we can pass delimiter value in the DictReader method as:
csv_values = csv.DictReader(f,delimiter=',')
Here we are specifying “,” as delimeter but we can specify other delimeters as required.
Writing CSV files
We can write values to csv files using the CSV module as:
data = [['employee_name', 'employee_id', 'department'],
['Emp1', '1', 'City1'],
['Emp2', '2', 'City2'],
['Emp3', '3', 'City3']]
with open(path, "a") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data: