CSV files are comma separated values and in literally stands for comma separated values. It is a commonly used data format and used by spreadsheets. Python has a csv module in it’s standard library that has classes and methods to perform read/write operations on CSV files. This is the basic stuff: You can change delimiter, newline, write a dictionary, write an iterable using writerows and more.
CSV Module in Python
There is a CSV module in python that has functions & classes available to help write and read CSVs, some of them are:
- csv.reader function
- csv.writer function
- csv.DictReader class
- csv.Dictwriter class
File Read/Write Modes in Python
Whenever we read from or write to a file in Python, we need to open it first. After completing the required tasks, we need to be close the file so that resources that are tied with the file are freed
- r for reading.
- r+ opens for reading and writing (cannot truncate a file)
- w for writing.
- w+ for writing and reading (can truncate a file)
- rb for reading a binary file. The file pointer is placed at the beginning of the file.
- rb+ reading or writing a binary file.
- wb+ writing a binary file.
- a+ opens for appending.
Create file and Write to CSV file
First of all you need to create a file and you simply call a function called “open” and specify that you want to write to it. If the file doesn’t exist Python will create it for you.
Here’s code example:
import csv with open('python.csv', 'w') as csvfile: filewriter = csv.writer(csvfile) filewriter.writerow(['Name', 'Address']) filewriter.writerow(['Arun', 'Delhi']) filewriter.writerow(['Vishal', 'New York']) filewriter.writerow(['Paul', 'Tokyo'])
Read CSV File
To read CSV file or any file for that matter of fact, simply use the open function. Here’s an example
import csv # create list holders for our data. names =  address =  # open file with open('python.csv', 'r') as f: reader = csv.reader(f) # read file row by row for row in reader: names.append(row) address.append(row) # Print data print names print address
In this tutorial we have covered most of what is required to successfully handle CSV file using the different functions and classes provided by Python. There’s a lot more but CSV files have been widely used in various ares as they are easy to read and manage plus their small size makes them relatively fast to process and transfer. If you are just getting started in Python in Windows, you’ll need PIP for majority of tasks, there are some more python tutorials that can help you in Video Format that you can find here:
Installing PIP in Windows