我對 Python 中的檔案處理和 csv 檔案相當陌生。
代碼
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()
我在這段代碼中試圖
- 按用戶輸入記錄(empID、Name、MobNo.)并制作一個 csv 檔案。
- 使用 empID 查找所需的記錄。
- 更新那個記錄。
- 顯示所有記錄。
當我執行代碼時,for 回圈中的列印陳述句在 if 陳述句之前執行并給我這個輸出。
輸出
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']
正如您在輸出的最后幾行中看到的那樣。Print 陳述句在 if 陳述句(或類似的東西)之前執行。我實際上希望輸出以下面給定的方式顯示......
期望輸出
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']
uj5u.com熱心網友回復:
我可以看到正在發生的事情,以及為什么它不是您所期望的。
看看這個塊:
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)
什么是實際發生的情況是,對于每一行x中empreader:
- ID col,
x[0], 正在根據您輸入的 ID 進行評估check。如果匹配:- 你中斷回圈,并介入修改
x - 寫出新值,
newwriter.writerow(x) - 然后你走出去......
- 你中斷回圈,并介入修改
- 列印您的更新,
print(x)
除非,x[0]==checkis False,在這種情況下x只是列印。
考慮(并測驗)當您為check...提供不存在的 ID 時會發生什么......它永遠不會進入您的“修改界面”,而只會列印empreader.
那么會發生什么,您是否顯示錯誤訊息讓用戶知道他們選擇了錯誤的 ID?
這是一個相當大的變化,但我認為它使邏輯和你的意圖更加清晰......你不是在回圈中做出決定,這非常困難。以“扁平”的順序接受輸入并做出決定:
import csv
import sys
# Get the employee ID
check=input("\nEnter the empID to check:\n")
# and check the ID in the employee records
emp_row = None
with open("Employee.csv","r",newline='\r\n') as f:
empreader=csv.reader(f)
for x in empreader:
if x[0] == check: # the employee ID matches
emp_row = x[:]
if emp_row is None:
print(f'Could not find employee ID {check}')
sys.exit(0) # or exit(1) to show it's an "error"
# Now you know you have a valid ID, because emp_row has data
opt=int(input('''Which of the following fields do you want to update?:
1.Update the Name
2.Update the Mobile No.
3.Update the whole record\n\n'''))
if opt == 1:
newname = input("Enter new name:")
emp_row[1] = newname
# else if opt == 2:
# ...
# else if opt ==3:
# ...
# Now how do you overwrite the old row in Employee.csv with emp_row?
# Don't try to "modify" the original file as you're reading it, instead...
# Read from the old file, copying all the old rows, except for emp_row, to a new list
new_rows = []
with open('Employee.csv', 'r', newline='\r\n') as f_in:
reader = csv.reader(f_in)
header_row = next(reader)
new_rows.append(header_row)
for row in reader:
if row[0] == check:
new_rows.append(emp_row)
else:
new_rows.append(row)
# Then write your new_rows out
with open('Employee.csv', 'w', newline='\r\n') as f_out:
writer = csv.writer(f_out)
writer.writerows(new_rows)
我從Employee.csv開始,看起來像這樣:
EmpID.,Name,MobNo.
001,John,1234567890
002,Jane,2345678901
003,Judy,4567890123
我運行了它,它看起來像這樣:
% python3 main.py
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
1
Enter new name:Alice
and Employee.csv now looks like:
EmpID.,Name,MobNo.
001,John,1234567890
002,Alice,2345678901
003,Judy,4567890123
(I'm on a Mac, so \r\n adding lines)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357399.html
上一篇:按型別重新分組的行的條件總和
