如何让我的程序为我提供CSV中某个单元格的值?

时间:2016-06-01 19:08:54

标签: python csv

我在尝试让我的程序在CSV文件中找到某个单元格时遇到问题。我的程序会要求您输入一个8位数字。如果它在CSV文件中,则应将该行写入文本文件。然后它应该继续询问用户他们想要购买多少产品。然后将该数量相乘以给出最终价格。价格将写入名为totalPrice的变量。

我最初的问题是数量,因为我无法从CSV文件中输入的GTIN-8号码行的第三列检索它。

我的代码是:

import csv
import sys
import re
import os

addItem = ""
gtinNum = ""
quantity = 0
totalPrice = 0
restart = ""

f = open("ChocolateCSV.csv", "rt")

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

    if restart.lower() == "y":
        gtinQuestion()
    else:
        print(receiptCont)
        sys.exit()

def quantityQuestion():
    quantity = input("How much would you like?")


def scanGTIN():
    global rows
    rows = re.split('\n', f.read())
    global receiptCont
    receiptCont = receipt.read()

   for index, row in enumerate(rows):
        global cells
        cells = row.split(',')
        if gtinNum in cells:
            receipt.write(receiptCont)
            receipt.close()
            quantityQuestion()

def gtinQuestion():
    global gtinNum
    global receipt
    receipt = open("receipt.txt", "r+")
    gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")

    if gtinNum.isdigit() == False or len(gtinNum) != 8:
        gtinQuestion()
    elif gtinNum.isdigit() == True and len(gtinNum) == 8:
        scanGTIN()


gtinQuestion()

1 个答案:

答案 0 :(得分:1)

您可以遍历csv文件的行并返回包含8位数字的行的特定列:

import csv

def get_row(filename, number, column):
    with open(filename, 'r') as f:
        for row in csv.reader(f):
            if str(number) in row:
                return row[column+1]