【问题标题】:Python - Add information to a list that is in another filePython - 将信息添加到另一个文件中的列表
【发布时间】:2019-08-16 09:25:41
【问题描述】:

将此程序称为文件 A:

vocabulary = []
while True:
   user_input = input('You: ')
   if user_input == 'vocabulary':
      print(vocabulary)
   vocabulary.append(user_input)

问题是,我希望附加到vocabulary 的信息是永久的,而不是每次运行程序时都清空。我该怎么做?

【问题讨论】:

标签: python python-3.x list python-3.6


【解决方案1】:

vocabulary 存储为外部文件。 Python 用于存储和保存 Python 对象的本机文件类型是使用 Pickle 模块的 .pkl 文件(pickle)。

我在您的代码示例中添加了一个外部文件,对词汇变量进行了腌制。

import pickle, os

if os.path.isfile('pkl.pkl'):
    with open('pkl.pkl','rb') as p:
        vocabulary = pickle.load(p)
else:
    vocabulary = []
while True:
    user_input = input('You: ')
    if user_input == 'vocabulary':
        print(vocabulary)
    vocabulary.append(user_input)
    with open('pkl.pkl', 'wb') as p:
        pickle.dump(vocabulary, p)

【讨论】:

    【解决方案2】:

    您可以使用 pickle 来保存您的对象 (How to pickle a list?),然后再次修改它等等。

    【讨论】:

    • 这不可能是一个可能的答案。它没有提供任何有价值的信息,而是指向另一个问题。您最好将此作为评论。
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2013-03-12
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2019-03-13
    • 2016-09-30
    相关资源
    最近更新 更多