【问题标题】:addition with python into a .txt file用 python 添加到 .txt 文件中
【发布时间】:2015-06-26 23:00:11
【问题描述】:

我正在使用 python 2.7.9 创建一个聊天室机器人,我想知道如何获取我在 .txt 文件中的数字并向其中添加一个数字,我卡住了,我想知道如何做到这一点,所以我可以向我的聊天室机器人添加货币。 我以前尝试过这样做,但我遇到了太多问题。 “args”是我要添加的参数/数字 “yp”是我使用的货币 这就是我所拥有的,但它不起作用 货币定义:

yp = []
f = open("yp.txt", "r")
time.sleep(1)
for currency in f.readlines():
    if len(currency.strip())>0: yp.append(currency.strip())
f.close()

我用来将数字保存到文件中的方法:

def saveyp(user):
f = open("yp.txt", "w")
f.write("\n".join(wl+args))
f.close()

还有我对机器人的命令:

if used_prefix and cmd == "test" and user.name in owners:
    if args:
        yp.append(yp+args)
        saveyp(yp+args)
        room.message("$"+args+" has been added to your currency :)")
        room.message(user.name.capitalize()+", you now have $"+yp)
    else:
        room.message("ERROR!")

【问题讨论】:

    标签: file python-2.7 bots addition


    【解决方案1】:

    我不确定您到底要做什么或遇到了什么错误,但文件中的数字将被编码为字符串,因此您需要先将其转换为整数,然后再将其添加到货币。也许这就是您遇到错误的地方?

    另外,在room.message(user.name.capitalize()+", you now have $"+yp) 之前,您需要在某处增加货币,以便打印更新后的金额。你会做这样的事情:

    yp += int(args)
    

    您所做的方式实际上并没有增加yp 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 2021-09-04
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      相关资源
      最近更新 更多