CSV内容被删除,我没有要求它,也无法写入

时间:2016-06-27 16:25:15

标签: python csv

我目前正在创建一个程序,允许用户使用GTIN代码订购产品或重新进货产品以便库存增加。但是,我遇到了一些我以前从未遇到过的问题。

1。删除CSV内容

首先,我尝试在quantityQuestionrestockAction中写入我的CSV文件 - 但是当我运行程序时,CSV的内容将被完全删除。

2。无法写入特定行

其次,我想在quantityQuestion的订单后更新库存。我写了row[2] = str(int(row[2]) - int(quantity)),以便数量基本上从自身中移除。我觉得这个问题好像与第一个问题有关。

3。代码

代码如下:

import csv
import sys

global totalPrice
totalPrice = 0

addItem = ""
gtinNum = ""
quantity = 0
restart = ""
price = 0

receipt = open("receipt.txt", "w+")
restockTxt = open("restock.txt", "w+")

def restart():
    restart = input("Would you like to restart? Y/N")

    if restart.lower() == "y":
        actionQ()
    else:
        print("Exiting program.")
        sys.exit()

def priceSub(): #Defining the restart subprogram
    priceQ = input("Would you like to add an item? Y/N") #Asks the user if they would like to add an item.
    global totalPrice #Declaring totalPrice and making it global.
    totalPrice = int(price) + totalPrice #Setting totalPrice to add the variable price to itself.

    if priceQ.lower() == "y": #If statement that checks to see if the user has entered a "y".
        gtinQuestion() #If it is true, it will start the gtinQuestion subprogram.
    else: #Anything other than a "y" will do the following commands.
        global receiptCont #Declaring the receipt content as a global variable.
        receiptCont = receipt.read() #Reads the receipt.
        receipt.close() #Closes the file.
        print(receiptCont) #Prints the content of the receipt.
        print("Total Price: " + "%.2f" % round(totalPrice, 2)) #Prints the totalPrice variable rounded to two decimal places.
        restart()

def quantityQuestion(): #Defining the subprogram for the quantity.
    quantity = input("How much would you like?") #Asks the user how much of the item they would like.
    if quantity.isdigit() == False: #If statement to check whether or not the user has entered an integer or not.
        quantityQuestion() #If they have not entered an integer, it will ask the question again.
    global price #Declaring the variable price as a global variable.
    price = "" #Setting price to an empty string.

    file2 = open("ChocolateCSV2.csv", "r")
    file2w = open("ChocolateCSV2.csv", "w", newline="")
    reader = csv.reader(file2, delimiter = ",")
    csvList = list(reader)

    for row in reader: #Loop that seperates each row in the CSV
        if str(gtinNum) in row: #If statement to check if the GTIN given by the user is in the CSV.
            receipt.write(str(row) + "\n") #If it is in one of the CSV rows, it will write the row to the text file.
            receipt.write(str("- Quantity: " + quantity + "\n")) #It also writes the quantity given by the user.
            price = float(row[2]) * int(quantity) #The price is the price given by the CSV file multiplied by the quantity.
            receipt.write("- Price: " + str("%.2f" % round(price, 2)) + "\n") #The final price (after the multiplication) is written to the text file also.
            row[2] = str(int(row[2]) - int(quantity))
            writeCSV = csv.writer(file2w)
            writeCSV.writerow(row)
            file2w.close()
            priceSub() #Starts the restart subprogram.
            break #Breaks the loop.
    else:
            print("The code entered could not be found - Please re-enter") #If it is not in the CSV it will print this error message.
            gtinQuestion() #Starts the gtinQuestion subprogram.

def gtinQuestion(): #Defining the gtinQuestion subprogram.
    global gtinNum #Declaring the gtinNum variable as global.
    gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:") #Setting that variable to the initial question.

    if gtinNum.isdigit() == False or len(gtinNum) != 8: #If the code given is not an integer or is not 8 digits long...
        print("Please re-enter your GTIN-8 code - Reason: Invalid Code") #It will print this error message and ask the question again.
        gtinQuestion()
    elif gtinNum.isdigit() == True and len(gtinNum) == 8: #If it is an integer and is 8 digits long...
        quantityQuestion() #It will start the quantityQuestion subprogram.

def restockAction():
    reader = csv.reader(file2, delimiter = ",")
    csvList = list(reader)
    global file2w
    file2w = open("ChocolateCSV2.csv", "w")
    file2 = open("ChocolateCSV2.csv", "r")

    for row in csvList:
        stDiff = float(row[5]) - float(row[3])
        if float(row[3]) <= float(row[4]):
            restockTxt.write(row[0]+" | "+row[1]+" | "+"Stock Replenished: "+(str(stDiff)+"\n"))
            restockTxt.close()
            row[3] = row[5]
            writeCSV = csv.writer(file2w)
            writeCSV.writerows(csvList)
            file2w.close()
    else:
            restockTxt.write("No (other) stock needs to be replenished.")
            restockTxt.close()
            restockRead = open("restock.txt", "r")
            print(restockRead.read())
            restart()

def actionQ():
    restock = input("What action would you like to perform?:\n Restock (Enter 1)\n Order (Enter 2)")

    if restock == "1" or restock == "restock":
        print("Restock Action Requested...")
        restockAction()
    elif restock == "2" or restock == "order":
        print("Ordering action Requested...")
        gtinQuestion()
    else:
        actionQ()

actionQ()

提前致谢 - 欢迎任何帮助

0 个答案:

没有答案