python - 在 csv 文件中编写嵌套字典,但标题在 csv 文件中每次都重复/附加
问题描述
我是python的新手。我已经编码在 csv 文件中附加嵌套字典。但是每次我运行代码时,标题也会被附加。
但我需要,标题应该只需要在 csv 文件中附加一次,不超过这个。
你有什么建议对我有帮助的修改吗?
提前致谢。
CSV file output
CSV 文件截图
User ID Name Age Occupation Department Salary Address
1100 Vishal 24 Data Scientist Analytics 75000 No.341, Kannagi Nagar, Okkiyam Thoraipakkam, chennai 97
User ID Name Age Occupation Department Salary Address
1101 MuraliKrishnan 45 Painting contractor Contract 50000 No.341, Kannagi Nagar, Okkiyam thoraipakkam, chennai 97
import csv
user_details = {}
while True:
user_input = input(" You're Operation Please ( New / View ) Details : ").lower()
if user_input == 'new':
create_user_ID = input(" Enter the user ID : ")
user_details[create_user_ID] = {}
user_name = input(" Enter the user name : ")
user_details[create_user_ID]['Name'] = user_name
user_age = int(input(" Enter the Age : "))
user_details[create_user_ID]['Age'] = user_age
user_occupation = input(" Enter the users occupation : ")
user_details[create_user_ID]['Occupation'] = user_occupation
user_department = input(" user department : ")
user_details[create_user_ID]['Department'] = user_department
user_income = int(input(" Enter the salary details : "))
user_details[create_user_ID]['Salary'] = user_income
user_address = input(" Enter the Address details ")
user_details[create_user_ID]['Address'] = user_address
print(f" New User account {create_user_ID} has been successfully created")
# Need to clarify this step,but program is running without any issues
with open('Employee Details.csv', 'a') as csvfile:
csv_columns = ['User ID', 'Name', 'Age', 'Occupation', 'Department', 'Salary', 'Address']
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for key,value in user_details.items():
row = {'User ID': key}
row.update(value)
writer.writerow(row)
process = input(" Do you want to continue the Account creation process (YES / NO ) : ").lower()
if process == 'no':
break
elif user_input == 'view':
user_ID = input("Enter the user_ID : ")
print(user_details[user_ID])
break
else:
print(" Please enter the proper command to execute (new / view)")
for detail in user_details.items():
print(detail)
解决方案
在while循环之前,检查文件是否存在;如果没有;创建带有标题的文件。在循环中只写行。
推荐阅读
- java - Spring Security 5.2 / WebClient 使用用户名和密码连接到另一个服务的方式是什么?
- r - 在 R - 对于所有 TRUE,所有后续 cols 都是 TRUE 吗?
- go - 在内存中编辑 zip 文件并通过 http 响应返回它会导致文件损坏
- xml - 删除 xml 标签之间的文本并仍然保留标签
- amazon-web-services - 通过 AWS CLI 更新 HTTP API 的 CORS 策略
- javascript - 如何使用 epub.js 在 HTML 中显示 epub 书籍的封面?
- excel - 如何在 VBA 中附加一个最初为空的字符串数组?
- javascript - 收到此错误:未捕获的 ReferenceError:未定义 mainLoop
- reactjs - 在 react 应用程序中通过 redux 调用 API 不起作用
- sass - 在最新版本的 SCSS 中使用 @use 时如何传递覆盖?