有没有办法将项目永久添加到列表文件?

时间:2019-08-25 12:57:19

标签: python python-3.x

我正在制作一个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)

3 个答案:

答案 0 :(得分:1)

尽管可以更新稍后导入的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()

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

答案 1 :(得分:0)

我不知道我是否正确解决了您的问题。让我表达我的想法。

我假设您想在从标准输入中获得g_list的更改后,将g_list的更改保存在其原始文件中。

g_list.py如下所示:

# g_list.py
guilds = ['a', 'b']

另一个名为g_add.py的文件,它提供添加操作:

# g_add.py
import pickle

from g_list import guilds


def g_add():
    # I think you want the `Guilds_Sorted.txt` be a temp file
    # and each time you run this script recreate that file.
    # use a `with` statement to do this so you don't need to
    # open and close the file manuallyy
    # the interpreter will do those jobs for you
    with open('Guilds_Sorted.txt', 'w'):
        pass  # since you just want to create a file, do nothing

    try:
        while True:
            guild = input("What is the guild's name ? ")
            with open('Guilds_Sorted.txt', 'a') as f:
                f.write(guild + '\n')
                guilds.append(guild)

            # if you want to change the original guilds in g_list.py
            # you may have to rewrite the g_list.py like this

            guilds.sort()  # sort it before you save
            with open('g_list.py', 'w') as f:
                f.write('guilds = [')
                for guild in guilds:
                    f.write("'" + guild + '",')
                f.write("]")

            # actually this is not so graceful...
            # if you really want to save the data in a list
            # you can refer to the `pickle` standard library
            # it looks like this
            # with open("g_list.pkl", "wb") as f:
            #     pickle.dump(guilds, f)

            # and when you want to use guilds
            # with open("g_list.pkl", "rb") as f:
            #     guilds = pickle.load(f)

    except KeyboardInterrupt:
        # you can exit by press `ctrl + c`
        print("exit...")


if __name__ == "__main__":
    g_add()

答案 2 :(得分:-1)

您可以使用附加标志a +打开并附加到文件:

f = open('Guilds_Sorted.txt','a+')