csv files with Python

The csv file extension stands for “comma separated values”. The data in the csv file is separated by commas hence the name. They are file formats that can be used to denote spreadsheets and databases. They are particularly useful in projects where you need to work with databases implicitly. Each value in the csv file denotes a particular column value for a given row in a database table.

The .csv file can be imported or exported into a program, making it available for viewing or manipulation.

To read data out of a csv file

import csv
with open('my_name.csv','r') as fsy:      #open the my_name file
reader = csv.reader(fsy) #store contents in reader

here ‘r’ specifies that file is to be opened in read mode. ‘rt’ can also be used which stands for read text. the data in the csv file is now stored in reader. Contents can be viewed by using print reader

similarly, to write data into a csv file

import csv
with open('my_name.csv','w') as fsy: #open the my_name file
writer = csv.writer(fsy) #write to file

Usually, it is better working with csv files in append mode in case you want to continuously be pushing values into it

import csv
sof = open('my_output.csv','a')
sof.write(var_name + ",") #write and move to next field in row
sof.write(var_name + "\n") #write and move to next row

If it is a new file being opened in append mode, push some values for the first row as append automatically jumps to the second row of the file. An empty first row results in problems later while parsing.

Remember to close the file after you are done working on it.

sof.close()

csv files are useful while transferring data from one program to another in a given project. They can be used as data-stores before and after processing.