如何在 Discord Py 中将列表附加并保存到另一个文件中?

Posted

技术标签:

【中文标题】如何在 Discord Py 中将列表附加并保存到另一个文件中?【英文标题】:How can I append and save a list into another file in Discord Py? 【发布时间】:2021-11-14 04:36:11 【问题描述】:

我基本上是在制作一些可以获取用户内容然后将其放入列表的内容。我想将它存储在另一个名为“问题”的文件中,我该怎么做?这是我的主要 Discord Bot 代码

import discord
import random
import problems

TOKEN = "SECRET"

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready!")

@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f"username: user_message (channel)")

    if message.author == client.user:
        return
    if message.channel.name == 'test':
        if user_message.lower() == 'hello':
            await message.channel.send(f"Hello username!")
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f"Bye!")
            return
        elif message.content.startswith("!store"):
            a = message.content[6:]
            await message.channel.send("Stored!")
            problemlist = problems.problem.append(a)
            print(problemlist)
    if user_message.lower() == '!code':
        await message.channel.send()
client.run(TOKEN)

这是我的问题的内部.py

problem = []

基本上是一个空列表 当它打印 problemlist 时我得到的是 None

另外,我希望该列表在机器人重新启动后仍然存在。

【问题讨论】:

您能否澄清您是否希望problems.py 中的变量保持不变(即,您是否希望该列表在您停止并重新启动机器人时仍然存在?) @HPringles 是的,我想 :) 【参考方案1】:

在 python(以及我知道的所有其他语言)中,当您导入另一个 python 文件时,它会将其作为代码加载,因此如果您的 problems.py 如上所述,它每次都会执行 problems = []脚本启动,一旦脚本启动,该内容就会从内存中清除。

如果您正在做一些非常简单的事情,最好的方法是将变量写入文件,使用picklejson。我在下面给出了一个阅读和写作的例子。

import json

def read(filename):
    """Open the file, read it and parse the json"""
    try:
        with open(filename, 'r') as json_file:
            return json.loads(json_file.read())
    except FileNotFoundError:
        return 

def write(filename, save_object):
    """Open the file, and write the object as json"""
    with open(filename, 'w') as json_file:
        json_file.write(json.dumps(save_object))

# Get the problems list if it exists.
problems = read('problems.json').get('problems', None) 
# If it doesn't create it.
if problems is None:
    problems = []
problems.append("problem")
write('problems.json', 'problems': problems)

这意味着problems.json 文件看起来像这样:


    "problems": [ "1", "2", "3", "4"]

【讨论】:

出于某种原因,它说Traceback (most recent call last): File "/home/denzel/Desktop/Bot/Denzelbot/Discordd/code.py", line 15, in <module> problems = read('problems.json').get('problems', None) File "/home/denzel/Desktop/Bot/Denzelbot/Discordd/code.py", line 7, in read with open(filename, 'r') as json_file: FileNotFoundError: [Errno 2] No such file or directory: 'problems.json' 我已经创建了一个problems.json 并在那里放置了一个空问题集。 抱歉,我会尽快更新我的答案。如果文件尚未创建,则无法从中读取。 不,我已经创建了一个它仍然说同样的话 很可能您在脚本不期望的位置创建了文件,请尝试更新您的代码以执行与上述类似的操作,这样应该可以解决问题。 对不起,我太笨了,没注意到你编辑了代码......谢谢它现在可以工作了!还想问一下有没有用pickle over json或者反之亦然的用例?

以上是关于如何在 Discord Py 中将列表附加并保存到另一个文件中?的主要内容,如果未能解决你的问题,请参考以下文章

如何在嵌入 discord.py 中将长字段作为页面发送?

需要一个关于将播放器保存在列表 discord.py 机器人上的问题的想法

在嵌入中附加文件 (Discord.py)

如何在 discord.py 中将字符串更改为不和谐 id

如何在 discord.py 中将图像裁剪为带有枕头的圆形?

如何在 discord.py 中将 on_message 与 sqlite3 集成?