I am fairly new to file handling and csv files in Python.
Code
import csv
file1=open("Employee.csv","w",newline='\r\n')
empwriter=csv.writer(file1)
empwriter.writerow(["EmpID.","Name","MobNo."])
n=int(input("How many employee records do you want to add?:"))
for i in range(n):
print("\nEmployee Record",(i+1))
empid=input("Enter empID:")
name=input("Enter Name:")
mob=input("Enter Mobile No.:")
emprec=[empid,name,mob]
empwriter.writerow(emprec)
file1.close()
file2=open("Employee.csv","r+",newline='\r\n')
empreader=csv.reader(file2)
newwriter=csv.writer(file2)
check=input("\nEnter the empID to check:\n")
opt=int(input('''Which of the following fields do you want to update?:
1.Update the Name
2.Update the Mobile No.
3Update the whole record\n\n'''))
if opt==1:
for x in empreader:
if x[0]==check:
newname=input("Enter new name:")
x[1]=newname
print("Record Updated Successfully!\n Updated record:\n",x)
newwriter.writerow(x)
print(x)
elif opt==2:
for x in empreader:
if x[0]==check:
newmob=input("Enter new Mobile No.:")
x[2]=newmob
print("Record Updated Successfully!\n Updated record:\n",x)
newwriter.writerow(x)
print(x)
elif opt==3:
for x in empreader:
if x[0]==check:
newname=input("Enter new name:")
newmob=input("Enter new Mobile No.:")
x[1]=newname
x[2]=newmob
print("Record Updated Successfully!\n Updated record:\n",x)
newwriter.writerow(x)
print(x)
file2.close()
I have in this code tried to
- enter records (empID, Name, MobNo.) by user and make a csv file.
- using empID find the desired record.
- update that record.
- display all records.
When I execute the code, the print statement inside the for loop gets executed before the if statement and gives me this output.
Output
How many employee records do you want to add?:3
Employee Record 1
Enter empID:001
Enter Name:John
Enter Mobile No.:1234567890
Employee Record 2
Enter empID:002
Enter Name:Jane
Enter Mobile No.:2345678901
Employee Record 3
Enter empID:003
Enter Name:Judy
Enter Mobile No.:4567890123
Enter the empID to check:
002
Which of the following fields do you want to update?:
1.Update the Name
2.Update the Mobile No.
3.Update the whole record
2
['EmpID.', 'Name', 'MobNo.']
['001', 'John', '1234567890']
Enter new Mobile No.:1111222233
Record Updated Successfully!
Updated record:
['002', 'Jane', '1111222233']
['002', 'Jane', '1111222233']
As you can see in the last few lines of the output. Print statement got executed before the if statement (or something similar).I actually want the output to display in the below given way...
Desired output
2
Enter new Mobile No.:1111222233
Record Updated Successfully!
Updated record:
['002', 'Jane', '1111222233']
['EmpID.', 'Name', 'MobNo.']
['001', 'John', '1234567890']
['002', 'Jane', '1111222233']
['003', 'Judy', '4567890123']