Reading and Writing CSV Files

A CSV, short for Comma-Separated Values, is a file format utilized for storing data in a structured table layout. All CSV files are composed of plain text and exclusively accommodate numerical and alphabetic characters. The information encapsulated within these files is organized in a tabular format, resembling a table.

Sample CSV File Data

column1,column2,column3,column4 data11,data12,data13,data14 data21,data22,data23,data24 data31,data32,data33,data34 data41,data42,data43,data44

The Python csv module encompasses classes designed for interacting with CSV files. There exist two distinct methods for parsing a CSV file. One option involves utilizing the reader function within the csv module, while an alternative approach entails using the capabilities of the DictReader class.

Usig csv.reader

The method csv.reader() serves the purpose of extracting data from a file structured in CSV format. Upon its invocation, this method yields a reader object, facilitating iteration over the CSV's lines. The data extracted is presented as a collection of strings, arranged in list form.

example
import csv with open('data.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: print(row)

Every row is returned as an array and can be accessed as such, to print the first cells we could simply write: row[0], row[1], row[2] etc.

import csv with open('data.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for col in reader: print(col[0], " : ",col[1], " : ", col[2], " : ", col[3])
output
column1 : column2 : column3 : column4 data11 : data12 : data13 : data14 data21 : data22 : data23 : data24 data31 : data32 : data33 : data34 data41 : data42 : data43 : data44

Using DictReader class

The DictReader class in Python essentially generates a CSV entity with behavior akin to that of a Python OrderedDict. This functionality is achieved by ingesting the initial line of the CSV, wherein each comma-separated value is employed as a key within a dictionary. In subsequent rows, the columns operate as dictionary values, thus permitting access via the corresponding keys.

example
import csv with open('data.csv') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') for line in reader: print(line["column1"], line["column2"],line["column3"],line["column4"])
output
data11 data12 data13 data14 data21 data22 data23 data24 data31 data32 data33 data34 data41 data42 data43 data44

Writing to CSV Files

Within the csv module, there exist two methods tailored for composing a CSV file. The choice lies between utilizing the writer function or opting for the DictWriter class. When engaging the writer object, two distinct functions are at your disposal: writerow() and writerows(). Evidently, the distinction between these functions is manifest in their nomenclature; writerow() is employed for composing an individual row, while writerows() is employed to craft multiple rows in a single operation.

example
import csv data = [['column1','column2'],['data11','data12'],['data21','data22']] csv_file = open('data1.csv', 'w') with csv_file: writer = csv.writer(csv_file) writer.writerows(data) print("Done")

Conclusion

CSV file operations are facilitated through the csv module, offering methods such as csv.reader() for reading CSV-formatted data into lists of strings, and DictReader for organizing data into dictionary-like structures. Writing CSV files is accomplished using the writer function or the DictWriter class, both of which allow the creation of single or multiple rows with the writerow() and writerows() functions respectively.