[英]Trying to edit a row of a csv file in python, but for some reason it also adds blank rows when run?
我正在努力做到這一點,以便您可以在 csv 文件中編輯單個客戶的詳細信息,雖然我編寫的代碼出於某種原因運行它會在每個客戶之間增加一個差距以及更改客戶 - 我真的很感激如果有人能告訴我為什么會這樣。
這是我的 csv 的摘錄:
first_name,last_name,title,pronouns,dob,occupation,account_balance,overdraft_limit
Genovera,Willgoss,Mrs,Female,25/05/2022,Graphic Designer,2315.16,46.48
Garner,Coupman,Ms,Male,14/04/2022,General Manager,2200.76,2.28
Jens,Eldrid,Honorable,Male,13/11/2021,Research Associate,967.64,79.15
我正在運行的代碼:
if choice == "4":
editClient = int(input("Please enter the index number of the client you wish to edit:"))
print("Please enter the details for each of the following:")
for i in range(len(existing_clients[0])):
newDetails = input("Enter new data for " + str(existing_clients[0][i]) + ":")
existing_clients[editClient][i] = newDetails
changes = input("Are you sure you'd like to make these changes? Enter Yes or No")
if changes == ("Yes"):
with open("mock_data.csv", "w+") as file:
reader = csv.writer(file)
for i in range(len(existing_clients)):
reader.writerow(existing_clients[i])
在我更換客戶后我的 csv 是什么樣子的:(我只是將 Jens 的所有詳細信息更改為 1)
first_name,last_name,title,pronouns,dob,occupation,account_balance,overdraft_limit
Genovera,Willgoss,Mrs,Female,25/05/2022,Graphic Designer,2315.16,46.48
Garner,Coupman,Ms,Male,14/04/2022,General Manager,2200.76,2.28
1,1,1,1,1,1,1,1
我沒有嘗試任何東西,因為我不知道是什么讓這一切發生——我只編程了一個月,我很迷茫。
我相信它在寫作時會添加一個額外的回車符。 嘗試更改此行:
with open("mock_data.csv", "w+") as file:
到
with open("mock_data.csv", newline= "", "w+") as file:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.