Comma-separated values (CSV) is a format to store data in the form of lines in a text file. Each line contains data fields separated by commas. It is the most common import and export format for spreadsheets and databases. Data are organised in tabular form with a first-line containing headers separated by commas.
item1, item2, item3,..
CSV files are imported into many spreadsheet programs like Excel. The first line of csv file contains headers of the data table.
header1, header2, header3,...etc. item1, item2, item3,..etc.
data are organised in a way similar to the 2-dimensional table:
In Python, The csv module offers classes to read and write tabular data in CSV format. It provides the user with methods to manage CSV files.
import csv reader = csv.reader(csvfile, dialect='excel', delimiter=",", quotechar="'") for row in reader: print(row) csvfile.close()
First import csv module. Read the csv file by the csv reader function, which gives all csv data in the iterator object named “reader”. You get each row by iterating through the reader.
Printing each row does not give us much satisfaction. It is better to print it as a table. Another module called “tabulate” will print the reader as a table. Install it through “pip install tabulate” and import it to your script.
from tabulate import tabulate import csv csvfile = open("acc.csv", "r") reader = csv.reader(csvfile, dialect='excel', delimiter=",", quotechar="'") data = list(reader) rows = data[1:] print(tabulate(rows, headers= data, tablefmt='fancy_grid', showindex=True, numalign="left"))