尝试使用python检查代码是否保存在文本文件中

尝试使用python检查代码是否保存在文本文件中,python,pickle,Python,Pickle,我正在制作一个程序,通过pickle模块保存物品及其代码、价格和数量 当有人想购物时,他们会输入一个代码。我正在尝试检查文本文档以查看该代码是否已保存,但它似乎不起作用,并导致以下错误: TypeError:类型为“NoneType”的参数不可编辑 有人能帮忙吗 stock = readfile() print("Please enter the GTIN-8 code of the items you want to buy, when you are done type DONE") whi

我正在制作一个程序,通过pickle模块保存物品及其代码、价格和数量

当有人想购物时,他们会输入一个代码。我正在尝试检查文本文档以查看该代码是否已保存,但它似乎不起作用,并导致以下错误:

TypeError:类型为“NoneType”的参数不可编辑

有人能帮忙吗

stock = readfile()
print("Please enter the GTIN-8 code of the items you want to buy, when you are done type DONE")
while True:
    code = input("Enter GTIN-8 code or DONE ")
    if code == "DONE":
        break
    else:
        amount = int(input("How many would you like? "))

if code in stock:
    print("Yes")
else:
    print("No")

readfile函数正在将stock变量设置为None。该函数可能存在问题,可能它实际上没有打开文件?

请尝试以下读取行:

def readlines():
    return [line.strip() for line in open('fruit.txt','r').readlines()]

为了多样性,这里有一个使用sqlite3的替代版本

注:货币按整数美分处理


错误在哪一行,什么是readfile错误在第66行,如果代码在库存中:那么库存必须是无的,那么只有你才能得到这个错误你可以共享readfile吗,看起来你没有从readfile返回任何东西为什么要使用pickle?sqlite似乎更适合这个任务。我在程序前面定义了readfile,我是这样做的:pickle.loadopenfruit.txt,rb@Connerreadfile不应该是def readfile:return pickle.loadopenfruit.txt,rb?它看起来好像加载了信息,但没有返回。因此它将返回None。这使得它现在没有错误,但是当我输入一个我知道是正确的代码时,它不会打印Yes。你能给我一个小的FROURT.txt片段和一个代码=。。。TXT是酸洗的,所以它很难理解,但这里你去欧元(Q席)} QX GTX 980QX 500 QX 10QEK] QX GTX 970QX 250QX也为GTIN -8代码的一个样本输入将是任何8位数字代码,如0000000 1。好,在未来更好的命名文件像水果。正在被pickle的对象是什么样子的?我不太清楚你的意思,我正在接受类似于此数据的输入。appendInput如果这是你的意思,请输入项目的名称
import sqlite3

DATABASE = 'stock.db'

def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            pass

def money_str(price, min_width=6):
    return "$ {1:{0:d}d}.{2:02d}".format(min_width - 5, price // 100, price % 100)

def make_stock_table(conn):
    conn.execute("DROP TABLE IF EXISTS Stock;")
    conn.execute(
        """
        CREATE TABLE Stock (
            code     INTEGER  PRIMARY KEY NOT NULL,
            name     TEXT     NOT NULL,
            price    INTEGER  NOT NULL,
            quantity INTEGER  NOT NULL  DEFAULT (0)
        );
        """
    )
    conn.commit()

def add_stock_code(conn, code, name, price):
    conn.execute(
        """
        INSERT OR REPLACE INTO Stock (
            code, name, price
        ) VALUES (
            ?, ?, ?
        );
        """,
        (code, name, price)
    )
    conn.commit()

def add_stock_quantity(conn, code, quantity):
    conn.execute(
        """
        UPDATE Stock
        SET quantity = quantity + ?
        WHERE code = ?
        """,
        (quantity, code)
    )
    conn.commit()

def buy_stock(conn, code, quantity):
    result = conn.execute("SELECT quantity, price FROM Stock WHERE code = ?", (code,)).fetchone()
    if not result:
        raise ValueError('No entry for code {}'.format(code))
    on_hand, price = result
    if on_hand < quantity:
        raise ValueError('Cannot buy {}, only {} on hand'.format(quantity, on_hand))
    conn.execute(
        """
        UPDATE Stock
        SET quantity = quantity - ?
        WHERE code = ?
        """,
        (quantity, code)
    )
    conn.commit()
    return quantity * price

def main():
    conn = sqlite3.connect(DATABASE)

    # create some test data
    make_stock_table(conn)
    add_stock_code(conn, 2429, "Golden Delicious Apples", 249)
    add_stock_quantity(conn, 2429, 20)
    add_stock_code(conn, 2514, "Macintosh Apples", 179)
    add_stock_quantity(conn, 2514, 35)

    # sell
    while True:
        code = get_int("Enter product GTIN-8 code (or 0 to quit): ")
        if code == 0:
            break
        quantity = get_int("How many would you like? ")
        try:
            cost = buy_stock(conn, code, quantity)
            print("Cost is {}".format(money_str(cost)))
        except ValueError as ve:
            print(ve)

if __name__ == "__main__":
    main()