Reading and writing csv files using python¶
Comma Separated Values - CSV¶
CSV is stands for comma separated values. CSV file format is most commonly used format for imports and exports of data to spreadsheets and databases.
Advantages to using CSV¶
- edit csv file manually with any text editor
- ease of parsing and implementing the data in csv
- faster to handle the csv and smaller file size
- csv is considered to be standard format
Disadvantages using CSV¶
- csv cannot deal with complex configurations
- No separation between numeric data and text data
- Some of the databases doesn't support csv files to import data
- No full support for special charactors
Reading and Writing CSV files in python¶
Python provides a in-built module
csv to read and write the csv files.
Writing csv files using python¶
# bulk writing csv files using python data = [ ('First Name', 'Last Name', 'City'), ('Ram', 'B', 'Warangal'), ('Naveen', 'M', 'Hyderabad'), ] with open('test.csv', 'a+') as csv_file: writer = csv.writer(csv_file, delimiter=',') writer.writerows(data) # write a row with open('test.csv', 'a+') as csv_file: row = ('Naveen', 'M', 'Hyderabad') writer = csv.writer(csv_file, delimiter=',') writer.writerow(row)
If we open a file using "with" statement we do not need to take care of closing of the file, It will close the csv file automatically. The function "writer" in module csv takes the file, delemeter as parameters and returns the writer object. The parameter "delemeter" is used to separate the columns in a row. we can write bulk rows to file at once using method "writerows". To write a single row use method "writerow" . Above code is the simple example for writing csv files using python.
Reading csv files using python¶
import csv with open('test.csv', 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: print(type(row)) # list for cell in row: print(cell) print "*" * 10
The function "reader" in module csv takes the file, delemeter as parameters and returns the "reader object". The parameter "delemeter" is used to separate the columns in a row. we can iterate through the reader object to get rows. each row in a reader object is a list. we can iterate through the row to get the column. Above code is the simple example for reading csv files using python.