python - 调用时的函数执行问题,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)
当我运行程序时,除了功能之外一切正常:(
有谁知道这个问题是什么?谢谢
解决方案
我建议您将代码布置得更像这样:
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() 定义一个类作为方法。现在,只是去程序。
推荐阅读
- node.js - 在 ubuntu 20.04.2 LTS 上安装 mongo db 时出错
- generics - 具有借入借入的构造函数的特征不能推断使用的提升时间
- python - 具有不同路径的图库,具体取决于型号名称
- python - ModuleNotFoundError:没有名为“pygame”的模块| VS 代码中的错误
- qt - 在从 QML 主窗口按下的按钮上打开一个 qt 小部件窗口
- javascript - 如何通过vue实例调用单独的js文件中的函数
- angular - 角度错误:无法设置未定义的属性
- android - 可以使用销毁的活动作为上下文调用 PreferenceManager.getDefaultSharedPreferences() 吗?
- algorithm - 按值为 MS 的列对数组进行排序。Excel 的行标签
- libcurl - curl_multi_fdset() 结合 poll()