You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord Py如何将列表存入外部文件并解决append返回None、数据持久化问题

问题1:append操作后赋值得到None的解决

Python中列表的append()是原地修改方法,不会返回修改后的列表,默认返回值为None,所以不需要接收返回值,直接执行追加操作即可。
原有错误代码:

problemlist = problems.problem.append(a)
print(problemlist)

修改为:

problems.problem.append(a)
print(problems.problem) # 直接打印原列表即可看到新增内容

问题2:列表数据持久化的解决

你当前用problems.py存储列表的方案仅能保存内存中的临时数据,程序退出后修改不会同步写入py文件,重启就会丢失。推荐用JSON文件做持久化存储,修改方案如下:

步骤1:删除原problems.py,新建problems.json文件

文件初始内容为:

[]

步骤2:修改主代码,加入JSON读写逻辑

完整修改后的代码如下:

import discord
import random
import json # 新增导入json模块

TOKEN = "SECRET"

client = discord.Client()
# 全局存储问题列表,启动时从json文件加载
problemlist = []

@client.event
async def on_ready():
    global problemlist
    # 启动时加载已有数据
    with open("problems.json", "r", encoding="utf-8") as f:
        problemlist = json.load(f)
    print("Bot is ready!")

@client.event
async def on_message(message):
    global problemlist
    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:].strip()
            # 追加到内存列表
            problemlist.append(a)
            # 同步写入json文件持久化
            with open("problems.json", "w", encoding="utf-8") as f:
                json.dump(problemlist, f, ensure_ascii=False, indent=2)
            await message.channel.send("Stored!")
            print(problemlist)
    if user_message.lower() == '!code':
        await message.channel.send()
client.run(TOKEN)

该方案每次新增数据都会同步写入本地JSON文件,机器人重启后会自动加载之前存储的所有内容,不会丢失。

内容的提问来源于stack exchange,提问作者airismything

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:09:00