The table below shows the names of three people living in three different cities.
We can represent the above table in CSV as :
SN, Name, City 1, Michael, New Jersey 2, Jack, California 3, Donald, Texas
A CSV (comma separated values) file is a readable text file where each line has different fields separated by a comma.
We use CSV file to store tabular data like the one we saw above. We can think each line as a row and each field as a column.
Python has inbuilt module i.e CSV, which is used for working with CSV files. In python, we use
csv.reader module to read a CSV file.
Here we are going to show how you can read a people.csv file, that we created in above example.
import csv with open('people.csv', 'r') as csvFile: reader = csv.reader(csvFile) for row in reader: print(row)
Once we run it on the python console, it will show following result :
['SN', 'Name', 'City'] ['1','Michael', 'New Jersey'] ['2','Jack', 'California'] ['3','Donald', 'Texas']
In above program,
csv.reader()method to extract the data into the reader object which we can iterate over to get each line of our data.
In python, we use
csv.Writer module to write in a csv file.
Here we are going to show how you can write to in a csv file. We will output some data stored in a python list into a csv file.
import csv csvData = [['Name of Person', 'Age'], ['Peter', '22'], ['Jasmine', '21'], ['Sam', '24']] with open('person.csv', 'w') as csvFile: writer = csv.writer(csvFile) writer.writerows(csvData)
When we run the above program, person.csv will contain the following data
Name of Person, Age Peter, 22 Jasmine, 21 Sam, 24
In the above code,