A CSV (Comma Separated Values) file is a text-based format that represents the data typically found in a spreadsheet or a database table.
It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV. It is also readily parseable with simple code.
Data within each column can be double-quoted to escape embedded commas in the data. Embedded double quotes are escaped with a pair of double-quote characters.
CSV files are also called flat files, as CSV files contain only simple formatted 2 Dimensional tables. Also, you do not need sophisticated software to handle CSV. You just need a simple text editor to manipulate the CSV files.
We have a built-in module for reading CSV files in Python, csv module helps to read CSV files in python language.
Sample CSV Files
Please save the below CSV content in your local system with .csv extension.
CSV file with a header
Name,Product,Description
karthiQ,chercher tech,tutorial
larry page,google,search engine
gates,microsoft,operating system
CSV file without header
karthiQ,chercher tech,tutorial
larry page,google,search engine
gates,microsoft,operating system
import unittest
import csv
class Test(unittest.TestCase):
def test_read_csv_file(self):
with open('D:PATHfile-without-header.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
print(row)
if __name__ == "__main__":
unittest.main()

In the above example, we have how to read the file with a header, but sometimes, we may have a CSV file with a header.
In such cases, we have to mark it as a header then we have to proceed reading; in this way, we have one more benefit that we can access the value using the headers as keys.
We can also read only required columns from the CSV file like below, and I have avoided the Product column from the CSV file.
We will be able to retrieve the columns using their names like row['title'].
import unittest
import csv
class Test(unittest.TestCase):
def test_read_csv_file(self):
with open('D:PATHfile-with-header.csv') as csvDataFile:
csvReader = csv.DictReader(csvDataFile)
for row in csvReader:
print(row['Name'], "--", row['Description'])
if __name__ == "__main__":
unittest.main()

In this program, we will learn how to read the URL from the CSV file and navigate to them in selenium python.
What happens in the below program :
import unittest
import csv
from selenium import webdriver
class Test(unittest.TestCase):
def readCSVFile(self, filename):
urls = []
titles = []
with open(filename) as csvDataFile:
csvReader = csv.DictReader(csvDataFile)
for row in csvReader:
urls.append(row['url'])
titles.append(row['title'])
return dict(zip(urls,titles))
def test_read_csv_file(self):
testObject = Test()
pages=testObject.readCSVFile("D:PATHfile-with-header.csv")
self.driver = webdriver.Chrome(executable_path=r'D:PATHchromedriver.exe')
print(pages)
for url,title in pages.items():
print(url)
self.driver.get(url)
self.assertEqual(title, self.driver.title, "title is not matching")
if __name__ == "__main__":
unittest.main()
Just like reading CSVs, the CSV module provides functions to write data to a CSV file as well. The writer object presents two functions, namely writerow() and writerows().
The difference between them is that the writerow() function will only write one row, and the function writerows() writes several rows at once.
import unittest
import csv
class Test(unittest.TestCase):
def test_write_csv_file(self):
myData = [["karthiq", "BE", "Mechanical"], ['Raj', 'BTech', 'Computers']]
myFile = open('csv-write-data.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(myData)
if __name__ == "__main__":
unittest.main()

We can also create a CSV file using dictionaries with the help of DictWriter. In the code below, we create a dictionary with the numbers and words.
Then we create a writer object that writes data to our number-values.csv file, which has the set of fields previously defined with the list myHeader.
We write the header row with the writeheader() function, and then the pairs of values using the writerow() function.
Each value's position in the row is specified using the column label.
import unittest
import csv
class Test(unittest.TestCase):
def test_write_csv_file(self):
myFile = open('number-values.csv', 'w')
with myFile:
myNumbers = ['number', 'word']
writer = csv.DictWriter(myFile, fieldnames=myNumbers)
writer.writeheader()
writer.writerow({'number' : '1', 'word': 'one'})
writer.writerow({'number' : '3', 'word': 'three'})
if __name__ == "__main__":
unittest.main()
Read CSV file which has '/' as a delimiter
import csv
csv.register_dialect('myDialect', delimiter='/', quoting=csv.QUOTE_NONE)
with open('greetings.csv', newline='') as myFile:
reader = csv.reader(myFile, dialect='myDialect')
for row in reader:
print(row)
Write CSV file which has '/' as a delimiter
import csv
myData = [[1, 2, 3], ['one', 'two', 'three']]
csv.register_dialect('myDialect', delimiter='/', quoting=csv.QUOTE_NONE)
myFile = open('numbers.csv', 'w')
with myFile:
writer = csv.writer(myFile, dialect='myDialect')
writer.writerows(myData)
I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.