首页 > 解决方案 > 有没有办法将项目永久添加到列表文件中?

问题描述

我正在制作一个 Python 脚本,它应该让我添加一个行会列表并按字母顺序对它们进行排序。因为我已经有了公会列表,所以我编写了一个 Python 文件,其中包含我已经拥有的名称列表。现在我需要将新项目附加到该列表中,因为该程序应该被多次使用,并且我需要在每次使用后将完整的列表与我输入的新项目一起保存。

这是我当前的代码:

from g_list import guilds  # imports the guilds list from the g_list.py folder


def g_add():
    f = open('Guilds_Sorted.txt','w')
    f.write("\n".join(guilds))
    f.close()
    while True:
        guild = input("What is the guild's name ? ") # can this input be saved back in the guilds list in g_list.py
        f = open('Guilds_Sorted.txt', "a")
        f.write('\n')
        f.write(guild)

标签: pythonpython-3.x

解决方案


尽管可以更新稍后要导入的 Python 文件,但这种情况极为罕见。

为什么不将初始公会存储在文本文件中,然后使用 Python 脚本向其中添加新公会?可以这样做:

PATH = 'Guilds_Sorted.txt'


def main():
    # First read the already saved guilds from the file into memory:
    with open(PATH, 'rt') as file:
        guilds = file.read().splitlines()

    # Now ask the user to add new guilds:
    while True:
        guild = input("What is the guild's name ? ")
        if not guild:
            break
        guilds.append(guild)

    # If you want, you can sort the list here, remove duplicates, etc.
    # ...

    # Write the new, complete list back to file:
    with open(PATH, 'wt') as file:
        file.write('\n'.join(guilds))


if __name__ == '__main__':
    main()

请注意,我添加了退出条件。通过不输入名称(空字符串),程序退出。


推荐阅读