CSV FINAL
CSV FINAL
AIM:
To create a csv file
- add () – To accept and add data of an employee to a CSV file ‘Empdata.csv’. Each record
consists of a list with field elements as Eid, Ename and salary to store employee id,
employee name and salary respectively.
- Update ()- To increase the salary of an employee.
SOURCE CODE:
import csv
FILE_PATH = "C:\\Users\\vimal\\OneDrive\\Desktop\\Empdat.csv"
"C:\\Users\\ravi\\OneDrive\\Desktop\\Empdat.csv"
def add():
# Open the file in append mode to add new records
with open(FILE_PATH, "w", newline='') as csvfile:
csvobj = csv.writer(csvfile)
csvobj.writerow(["Eid", "Ename", "Salary"])
while True:
Eid = input("Enter Employee ID: ")
Ename = input("Enter Employee Name: ")
Salary = input("Enter Employee Salary: ")
csvobj.writerow([Eid, Ename, Salary])
ch = input("Do you want to add another record? (Y/N): ")
if ch.upper() == "N":
break
print("Employee data added successfully.\n")
def update():
with open(FILE_PATH, "r", newline='') as csvfile:
csvobj = csv.reader(csvfile)
rows = list(csvobj)
Eid = input("Enter the Employee ID to update salary: ")
Salary_increase = input("Enter the amount to increase the salary: ")
updated = False
for i, row in enumerate(rows):
if row[0] == Eid:
try:
row[2] = str(int(Salary_increase))
updated = True
except ValueError:
print("Invalid salary or increment value. Update failed.\n")
return
if not updated:
print("Employee ID not found. No changes made.\n")
return
# Write the updated data back to the file
with open(FILE_PATH, "w", newline='') as csvfile:
csvobj = csv.writer(csvfile)
csvobj.writerows(rows)
# Main Program
while True:
print("1. Add Employee Data")
print("2. Update Employee Salary")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == "1":
add()
elif choice == "2":
update()
elif choice == "3":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.\n")
SAMPLE OUTPUT:
RESULT:
Thus the above program is successfully executed and the output is verified.