CSV Module in Python
The csv module in Python is used to read from and write to CSV (Comma Separated Values)
files. CSV files are commonly used to store tabular data such as employee details, student
records, etc.
1. Importing CSV Module
import csv
def insert_record():
with open('[Link]', 'a', newline='') as file:
writer = [Link](file)
emp_id = input("Enter Emp ID: ")
name = input("Enter Name: ")
salary = input("Enter Salary: ")
[Link]([emp_id, name, salary])
print("Record Inserted Successfully")
read:
import csv
def read_records():
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
2. Single Record Insert
This example shows how to insert a single record into a CSV file.
import csv
with open('[Link]', 'a', newline='') as file:
writer = [Link](file)
[Link]([101, 'Ajay', 50000])
3. Multiple Records Insert
This example shows how to insert multiple records into a CSV file.
import csv
records = [
[102, 'Ravi', 60000],
[103, 'Sita', 55000],
[104, 'Kiran', 52000]
]
with open('[Link]', 'a', newline='') as file:
writer = [Link](file)
[Link](records)
4. Update Record in CSV File
CSV files do not support direct update. We must read data, modify it, and write it back.
import csv
updated_rows = []
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
if row[0] == '101':
row[2] = '70000'
updated_rows.append(row)
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](updated_rows)
5. Delete Record from CSV File
To delete a record, we read all records except the one to be deleted and write them back.
import csv
remaining_rows = []
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
if row[0] != '103':
remaining_rows.append(row)
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](remaining_rows)
6. Conclusion
The csv module is simple and powerful for handling CSV files. It is commonly used in
automation, data processing, and beginner-level projects.