Introduction
Handling files is essential in any language, either a standard text file or a specific format file like CSV or JSON files, so let's understand how we can use Python to handle and do read and write operations with CSV and JSON files.
Let's first understand the format of a CSV file.
The CSV (Comma Separated Values) file format is a simple way to save tabular data in spreadsheets and databases. A CSV file is a plain text file with tabular data (numbers and text). Each line in the file represents a data record. There are one or more fields in each entry separated by commas. Using a comma as a field separator gives this file format its name.
JSON stands for JavaScript Object Notation in its entire form. The data is stored and transferred using a script (executable) file written in a computer language. In JSON, the text is represented as a quoted string containing the value in a key-value mapping.
a ={"name":"John",
"age":31,
"Salary":25000}Having understood the basics of CSV and JSON, let's see how we can handle them in Python.
Also See, Floor Division in Python, Swapcase in Python
Handling CSV files in Python
There is an inbuilt module in Python that is used to specially handle CSV files in Python, the module is CSV, and we have to import it and use it to manipulate CSV files.
There are two kinds of entries in a CSV file: Fields, the column's name, and Rows.
Also See, Python Round Function and Convert String to List Python.
Reading CSV files in Python
Reading in CSV file is done through CSV.reader, which opens the file to read; the argument to this function is the '/file/path', and then we can run functions on the output of this function.
Let's understand from code.
The CSV file we are using is addresses.csv which can be downloaded from here.
Code:
import csv # importing the csv module.
# csv file path
filename = "addresses.csv"
#opening the csvfile in traditional way
csvfile=open(filename,'r')
# initializing the titles and rows list
fields = []
rows = []
# reading CSV file
# creating a CSV reader object
csvreader = csv.reader(csvfile)
#this object is our go-to for every change in the
# we will just interact with it.
# csvreader is an iterator it has the data in the form of rows
# a next is called on it, then it goes to the next row.
# so the first row will have fields, and correspondingly we can
# go for next.
# extracting field names through first row
fields = next(csvreader)
# next function returns the current row and
#advances the row to the next.
# extracting each data row one by one
# in for loop next is automatically called for
# an iterator.
for row in csvreader:
rows.append(row)
# get total number of rows
print("Total no. of rows: %d"%(csvreader.line_num))
# printing the field names
print('Field names are:' + ', '.join(field for field in fields))
# printing first 5 rows
print('\nFirst 5 rows are:\n')
for row in rows[:5]:
# parsing each column of a row
for col in row:
print(col,end=" ")
print('\n')Output:
Total no. of rows: 6
Field names are: John, Doe, 120 Jefferson st., Riverside, NJ, 08075
The First 5 rows are:
Jack McGinnis 220 hobo Av. Phila PA 09119
John "Da Man" Repici 120 Jefferson St. Riverside NJ 08075
Stephen Tyler 7452 Terrace "At the Plaza" road SomeTown SD 91234
Blankman SomeTown SD 00298
Joan "the bone", Anne Jet 9th, at Terrace plc Desert City CO 00123 The main things to note in this program are already mentioned in the comments, but still focusing on csvreader, which has been returned by CSV.reader(filename) as an iterator to the file. It stores values of the rows, the next function returns the current row and moves the iterator to the next row, and this is how we can iterate through the whole CSV file.
You can practice by yourself with the help of online python compiler.
Writing on CSV files in Python
import CSV
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
# name of csv file
filename = "student_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)This is a simple example to write the data to a CSV file; there are a lot more utilities to write the data in CSV; if you have a dictionary of data to be written to CSV, we can use another function CSV.dictwriter(filename), which will take an array of dictionaries and automatically make CSV out of them.
import CSV
# my data rows as dictionary objects
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]
# field names
fields = ['name', 'branch', 'year', 'cgpa']
# name of csv file
filename = "university_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames = fields)
# writing headers (field names)
writer.writeheader()
# writing data rows
writer.writerows(mydict)Like these, many more functions can be used, but mostly above-explained functions are enough in most use cases. For more functionalities, have a look at this page:





