CSV File
CSV (Comma Separated Values) is a plain text file that stores tabular data. Each
line is a row, and each value is separated by a comma.
Example
Name Age City
Name,Age,City
John,25,New York John 25 New York
Alice,30,London Alice 30 London
Bob,22,Sydney Bob 22 Sydney
Importing the csv Module
import csv
Opening and Closing a CSV File
with open('[Link]', 'mode') as file:
'w' = write (overwrite)
'a' = append
'r' = read
Writing to a CSV File
1. [Link]()
This creates a writer object.
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
Use newline='' to prevent extra blank lines on Windows.
2. [Link]()
Writes a single row (as a list):
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](['Name', 'Age', 'City'])
[Link](['John', 25, 'New York'])
3. [Link]()
Writes multiple rows (a list of lists):
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](['Name', 'Age', 'City']) # Header
rows = [
['Alice', 30, 'London'],
['Bob', 22, 'Sydney'],
['Eva', 28, 'Toronto']
[Link](rows)
Reading from a CSV File
1. [Link]()
Reads the file row by row (returns an iterator):
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
Each row is returned as a list of strings.
Complete Example
import csv
def Write():
f=open("D:/[Link]","w",newline='')
wo=[Link](f ,delimiter=';')
[Link](["RollNo", "Name", "Stream", "Marks"])
while True:
rno=int(input("Roll No.:"))
name=input("Name:")
stream=input("Stream:")
marks=int(input("Marks:"))
data=[rno, name, stream, marks]
[Link](data)
ch=input("More (Y/N)?")
if ch in 'Nn':
break
[Link]()
def Read():
f=open("D:/[Link]","r", newline='')
ro=[Link](f)
for i in row:
print(i)
Write()
Read()