修复excel/csv导入导出 [英] fix excel/csv imports exports

查看:47
本文介绍了修复excel/csv导入导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正开始学习Python尝试学习.

I am at the beginning of learning Python trying to learn.

程序的概念是应用".一家咖啡店接受订单[![在此处输入图片描述] [1]] [1]

The concept of the program is an "Application" for a coffee shop to take orders [![enter image description here][1]][1]

        if Customer_Name in Customers:
            Customers[Customer_Name]['Orders'] += 1
            Customers[Customer_Name]['TotalAmount'] = Total_Amount
        else:
            Customers[Customer_Name] = {}
            Customers[Customer_Name]['Name'] = Customer_Name
            Customers[Customer_Name]['Address'] = Customer_Address
            Customers[Customer_Name]['ID'] = uuid.uuid1()
            Customers[Customer_Name]['Orders'] = 1
            Customers[Customer_Name]['TotalAmount'] = 0

        print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
        if Customers[Customer_Name]['TotalAmount'] == 0:
            print("This is the first time", Customer_Name, "orders")
        else:
            print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")

        print("Current Date is: {}".format(Today_Date))
        Order_Price = float(input("Total amount of order:"))
        Total_Amount = Order_Price + Total_Amount
        if Print_Today != Today_Date:
            print("Total amount of orders today is: ", float(Total_Amount))
        answer1 = input("Send another order? (Y/N)").lower()
        process2 = answer1 == "y"
    LengthCustomersList = len(Customer_List)
    length += 1
    in_list += 1

    file.write(str(Customer_List[0:]) + '\n')  # TAKE CARE FOR DUPLICATE NAMES FROM SAME ADDRESS


    file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
    # FIX DUPLICATES SAME NAME SAME ADDRESS


    csv_writer = DictWriter(open('data_entered.csv','a'), fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
                                           'Total Amount'])
    csv_writer.writeheader()
    csv_writer.writerows([{'Customer Name': Customers[Customer_Name]['Name'],'Customer Address': Customers[Customer_Name]['Address'],
                           'Customer ID': Customers[Customer_Name]['ID'],
                           'Total Orders': Customers[Customer_Name]['Orders'],
                           'Total Amount': Customers[Customer_Name]['TotalAmount']}])  # TOTAL AMOUNT= 0 IF NOT MORE THAN 2 TIMES ORDER






    if int(length) == int(LengthCustomersList):
        process1 = False
file.close()
file1.close()
file2.close()

这是我当前得到的输出

[![输出] [2]] [2]

[![Output][2]][2]

问题是:为什么它只导入两次输入的名称,而在这种情况下不导入米歇尔.

The question is: Why does it only import the name that it gets inputted twice, and not Michelle in this case.

PS *.我想了解如何解决此问题.所以,请不要只是直接给我解决方案

PS*. I would like to understand how to fix this. So please don't just give me the solution straight up

推荐答案

您似乎并没有遍历 Customers 字典以便将其添加到CSV文件.您可以使用 Customers 嵌套词典的 .keys()属性,并遍历每个客户词典.在循环内部,使用 .writerow()函数添加当前客户的数据.

It looks like you don't loop through the Customers dictionary in order to add it to the CSV File. You can use the .keys() attribute of the Customers nested dictionary and loop through each customer dictionary. Inside the loop, use .writerow() function to add the data of the current customer.

我对代码的更改:

# Rest of the code 

csv_writer = DictWriter(open('data_entered.csv', 'a'),
                            fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
                                        'Total Amount'])
    csv_writer.writeheader()
    for customer_name in Customers.keys():
        csv_writer.writerows(
            [{'Customer Name': Customers[customer_name]['Name'], 'Customer Address': Customers[customer_name]['Address'],
              'Customer ID': Customers[customer_name]['ID'],
              'Total Orders': Customers[customer_name]['Orders'],
              'Total Amount': Customers[customer_name]['TotalAmount']}])  # TOTAL AMOUNT= 0 IF NOT MORE THAN 2 TIMES ORDER

完整代码:

import uuid  # GET A RANDOM ID FOR THE CUSTOMER
from datetime import date  # GET CURRENT DATE
from csv import DictWriter

file = open('CustomerNames.txt', 'w')
file1 = open('Orders_Per_Users.txt', 'a')
file2 = open('data_entered.csv', 'a')
x = -1
in_list = -1
length = 0
Total_Amount = 0.0
Customer_List = []
Address_List = []
Today_Key = date.toordinal(date.today())
Today_Date = date.today()
Print_Today = Today_Date
Customers = {}
Dates = {}
FirstEmployeeAccountUsername = "coffee1"
FirstEmployeeAccountPassword = "coffeeshop1"
SecondEmployeeAccountUsername = "coffee2"
SecondEmployeeAccountPassword = "coffeeshop2"
ThirdEmployeeAccountUsername = "coffee3"
ThirdEmployeeAccountPassword = "coffeeshop3"

print("Welcome to our coffee shop!")
print("Login")

# EMPLOYEE LOGIN PROCESS STARTS
LoginEnter = True
while LoginEnter:
    username = input("Username: ")
    password = input("Password: ")
    if username == FirstEmployeeAccountUsername and password == FirstEmployeeAccountPassword or username == SecondEmployeeAccountUsername and password == SecondEmployeeAccountPassword or username == ThirdEmployeeAccountUsername and password == ThirdEmployeeAccountPassword:
        print("Login Successful")
        LoginEnter = False
    else:
        print("Invalid Login. Try again")
# EMPLOYEE LOGIN PROCESS ENDS


# PROCESS AFTER ORDER PLACEMENT STARTS
process1 = True
process2 = True
while process1:
    while process2:
        x += 1

        Customer_Name = input("Customer's Name:")
        Customer_Address = input("Customer's Address:")
        Address_List.append(Customer_Address)
        Customer_List.append(Customer_Name)
        if x == 1:
            if Customer_Address in Address_List:
                First_Index = Address_List.index(Customer_Address)
                if Customer_Name == Customer_List[First_Index]:
                    Customer_List.pop(First_Index)
                    Address_List.pop(First_Index)

                    x = x - 1

        if Today_Key not in Dates:
            Dates[Today_Key] = {}
            if Customer_Name not in Dates[Today_Key]:
                Dates[Today_Key][Customer_Name] = 1
            else:
                Dates[Today_Key][Customer_Name] += 1

        if Customer_Name in Customers:
            Customers[Customer_Name]['Orders'] += 1
            Customers[Customer_Name]['TotalAmount'] = Total_Amount
        else:
            Customers[Customer_Name] = {}
            Customers[Customer_Name]['Name'] = Customer_Name
            Customers[Customer_Name]['Address'] = Customer_Address
            Customers[Customer_Name]['ID'] = uuid.uuid1()
            Customers[Customer_Name]['Orders'] = 1
            Customers[Customer_Name]['TotalAmount'] = 0

        print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
        if Customers[Customer_Name]['TotalAmount'] == 0:
            print("This is the first time", Customer_Name, "orders")
        else:
            print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")

        print("Current Date is: {}".format(Today_Date))
        Order_Price = float(input("Total amount of order:"))
        Total_Amount = Order_Price + Total_Amount
        if Print_Today != Today_Date:
            print("Total amount of orders today is: ", float(Total_Amount))
        answer1 = input("Send another order? (Y/N)").lower()
        process2 = answer1 == "y"
    LengthCustomersList = len(Customer_List)
    length += 1
    in_list += 1

    file.write(str(Customer_List[0:]) + '\n')  # TAKE CARE FOR DUPLICATE NAMES FROM SAME ADDRESS

    file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
    # FIX DUPLICATES SAME NAME SAME ADDRESS

    csv_writer = DictWriter(open('data_entered.csv', 'a'),
                            fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
                                        'Total Amount'])
    csv_writer.writeheader()
    for customer_name in Customers.keys():
        csv_writer.writerows(
            [{'Customer Name': Customers[customer_name]['Name'], 'Customer Address': Customers[customer_name]['Address'],
              'Customer ID': Customers[customer_name]['ID'],
              'Total Orders': Customers[customer_name]['Orders'],
              'Total Amount': Customers[customer_name]['TotalAmount']}])  # TOTAL AMOUNT= 0 IF NOT MORE THAN 2 TIMES ORDER

    if int(length) == int(LengthCustomersList):
        process1 = False
file.close()
file1.close()
file2.close()

有关 .keys()和其他词典内置方法的更多信息:

More information on .keys() and other dictionary built-in methods: https://www.w3schools.com/python/python_ref_dictionary.asp

这篇关于修复excel/csv导入导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆