【问题标题】:How do I make my program give me the value of a certain cell in a CSV?如何让我的程序为我提供 CSV 中某个单元格的值?
【发布时间】:2016-06-01 19:08:54
【问题描述】:

我在尝试让我的程序在 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()

【问题讨论】:

    标签: python csv


    【解决方案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]
    

    【讨论】:

    • 这是学校的一些功课,所以第一个解决方案可能比使用 Pandas 的解决方案更好。虽然,Pandas 看起来是更好的选择。让我看看第一个解决方案。
    • 我想我最初误读了这个问题。像这样的东西可能更适合在 csv 文件中获取您需要的行。
    • 运行时出现错误 _csv.Error: iterator 应该返回字符串,而不是字节(您是否以文本模式打开文件?)
    • 你用的是什么版本的python?尝试在open 函数中将'rb' 替换为'r'
    • 它没有给出'r'的错误,但我想获取该行第三列中的值(或第二个逗号后的值)@pbreach
    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多