写入外部模块中的列表

Writing to a list in an external module

所以我正在开发一个 discord 机器人,它具有 meme 命令、roast 命令等命令,并且由于我仍在学习 python 我还没有开始使用数据库和存储所有的烤肉都放在一个单独的 py 文件中,然后将其作为模块导入 bot 文件中。

我想创建另一个 .py 文件来导入列表并附加到它,而不是我打开 py 文件并自己编辑它...这是我现在编写的代码,即使它执行时没有任何错误,列表模块不会追加。

from roasts_list import roast

adder_value = input("What would you like to add? \n")
roast.append(adder_value)

模块是 roasts_list,列表名称是 roast。

有什么解决办法吗?

无需创建外部 python 模块来存储列表,您可以将其存储在文本文件中。

adder_value = input("What would you like to add? \n")

#add roasts to the text file

roast_file = open("roast.txt", "a")
roast_file.write(adder_value + "\n") #adds roast to the text file
roast_file.close()

#get roasts

roast_file = open("roast.txt", "r")
roast_list = roast_file.read().splitlines() #returns a list of all roasts in the text file
roast_file.close()

使用此方法,您可以将烤肉保存在文本文件中,并相应地使用它们。

同意 Devansh 的观点。如果您按照自己的方法将它们保存在例如来自 .py 文件的列表变量,这意味着您的所有值只会存储在内存中,一旦程序停止,所有值都将丢失。如果要持久存储值,最简单的方法是将它们存储在文件中。

除了上述 Devansh 方法之外,我建议使用其上下文管理器打开文件,并添加一个 try/except 来处理如果您尝试在文件创建之前从文件中获取烤肉,使它有点在 运行 程序中更稳定。

#add roasts to the text file
def add_roast():
    adder_value = input("What would you like to add?  ")
    with open("roast.txt", "a") as roast_file:
        roast_file.write(adder_value + "\n") #adds roast to the text file

#get roasts
def get_roasts():
    try:
        with open("roast.txt", "r") as roast_file:
            return roast_file.read().splitlines()
    except FileNotFoundError as e:
        print("No roasts exist yet")

add_roast()
print(get_roasts())