首页 > 解决方案 > 调用时的函数执行问题,python

问题描述

我有一个小型 python 程序,只能在 csv 文件中编辑一行,我通过获取文件的所有行和列并用用户输入的内容替换选定的行来做到这一点。

关键是我有一个函数被激活取决于选择了哪一行但无法激活,我已经尝试了很多方法,我已经调用它清楚了,这个函数还没有执行。

我已经有了代码,但我只需要激活该功能。

这是我的代码的一个小例子:

import pandas as pd

my_variable = "ninguna"

new_variable1 = "hello"
new_variable2 = "How are you"
new_variable3 = "brother"

if my_variable == "none":
    with open("priv/productos.csv", 'r') as edit:
        edit = edit.read()
    def edit_row(self):
        def tryloc(df, col, idx, default=None):
            try:
                return df.iloc[col, idx]
            except IndexError:
                return default
        print("the variable if it is running")
        edit = pd.read_csv("priv/products.csv")
        
        product_2 = tryloc(edit, 1, 0)
        brand_2 = tryloc(edit, 1, 1)
        price_2 = tryloc(edit, 1, 2)
        
    
        with open("priv/products.csv", 'w') as login_main:
            login_main.write("PRODUCTS" +",")
            login_main.write("BRANDS" +",")
            login_main.write("PRICES" +"\n")
            
            login_main.write(str(new_variable1) +",")
            login_main.write(str(new_variable2) +",")
            login_main.write(str(new_variable3) +"\n")
        
            login_main.write(str(product_2) +",")
            login_main.write(str(brand_2) +",")
            login_main.write(str(price_2) +"\n")
                  
        edit_row(self)

当我运行程序时,除了功能之外一切正常:(

有谁知道这个问题是什么?谢谢

标签: python

解决方案


我建议您将代码布置得更像这样:

import pandas as pd

def edit_row(filename):
    with open(filename, 'r') as edit:
        data = edit.read()
        # lines to edit data here
    # lines to save edited data here

edit_row("priv/productos.csv")

您现在所拥有的是 my_variable 包含字符串“ninguna”,并且仅在 my_variable 包含字符串“none”时才执行定义和调用 edit_row() 的行。因此,当您运行代码时,将跳过定义和对 edit_row() 的调用。

您的代码还假定 edit_row() 是一个名为 edit 的对象的方法,该对象的类从未定义。为此,您需要使用 edit_row() 定义一个类作为方法。现在,只是去程序。


推荐阅读