Reading and Writing CSV Files in Python
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Program 1
import csv
try:
filename=input("Enter a file name for create: ")
f=open("d://mydata/"+filename+".csv","w",newline='')
if(f.writable()):
obj=csv.writer(f)
obj.writerow(['eno','ename','salary','department'])
while True:
en=int(input("Enter Employee Number: "))
name=input("Enter Name: ")
sal=int(input("Enter Salary: "))
dept=input("Enter Department Name: ")
obj.writerow([en,name,sal,dept])
choice=input("Are you sure want ot continue(Yes/No)")
choice=choice.upper()
if(choice=='NO'):
break
else:
print("Read only file.....")
except Exception as obj:
print(obj)
finally:
f.close()Program 2
#Program to read data from CSV file
import os,csv
try:
filename=input("Enter a file name for create: ")
if(os.path.isfile("d://mydata/"+filename+".csv")):
f=open("d://mydata/"+filename+".csv","r")
obj=csv.reader(f)
mylist=list(obj)
for row in mylist:
for col in row:
print(col,end=" ")
print()
f.close()
else:
print("Invalid file name.....File not found")
except Exception as obj:
print(obj)
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

