Reading Time: 1 minutes
csv in Python
CSV (Comma-separated values) is a common data interchange format. Python's csv library makes it easy to work with files containing comma-separate values. Its reader() method can be used to read CSVs, while its writer() method helps to write to them.
>>> import csv |
# The writerow() method of the writer object returned by writer() writes a sequence to the specified file with the given delimiter. |
>>> with open ( 'csvFileOne.csv' , 'w' , newline = '') as csvFile: |
csvWriter = csv.writer(csvFile, delimiter = ',' ) |
csvWriter.writerow([ 'New Delhi' , 'India' , 'Asia' ]) |
csvWriter.writerow([ 'New Jersey' , 'U.S.A.' , 'North America' ]) |
# Contents of csvFileOne.csv |
New Delhi,India,Asia |
New Jersey,U.S.A.,North America |
# reader() returns an iterator of records in the CSV file. |
>>> with open ( 'csvFileOne.csv' ) as csvFile: |
csvReader = csv.reader(csvFile, delimiter = ',' ) |
for record in csvReader: |
print ( ', ' .join(record)) |
|
New Delhi, India, Asia |
New Jersey, U.S.A., North America |
>>> with open ( 'csvFileOne.csv' ) as csvFile: |
csvReader = csv.reader(csvFile, delimiter = ',' ) |
for city, country, continent in csvReader: |
print ( '{}, {}, {}' . format (city, country, continent)) |
|
New Delhi, India, Asia |
New Jersey, U.S.A., North America |