首页 > 解决方案 > 在 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)

标签: pythonpython-3.x

解决方案


在while循环之前,检查文件是否存在;如果没有;创建带有标题的文件。在循环中只写行。


推荐阅读