Python将项目添加到列表?

时间:2013-12-18 17:32:00

标签: python list python-3.3

当我将项目添加到列表list.append()list.insert()或任何其他方法时,当我加载文件时,我添加到列表中的项目不存在。另外我想在另一个文件中列出这个列表以防它有任何区别。

代码:

User = ["pig"]
Pass = ["ham"]
User.insert(len(User)+1, "cow")
Pass.append("beef")

我知道如何从其他文件中获取内容。

2 个答案:

答案 0 :(得分:1)

try: #load list from file if it (the file) exists
   my_list = json.load(open("my_database.dat"))
except IOError: #otherwise create the list
   my_list = []
...
#save list for next time ..
json.dump(my_list,open("my_database.dat","wb"))

是执行此操作的众多方法之一

你也可以使用泡菜

try: #load list from file if it (the file) exists
   my_list = pickle.load(open("my_database.dat"))
except IOError: #otherwise create the list
   my_list = []
...
#save list for next time ..
pickle.dump(my_list,open("my_database.dat","wb"))

或用ast.literal_eval

try:
    my_list = ast.literal_eval(open("some_file").read())
except IOError:
    my_list = []
...
#save list
with open("some_file","wb") as f:
     f.write(repr(my_list))

答案 1 :(得分:0)

对于良好开始的运行pickle之间的简单数据持久性:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pickle

def main():

    # Load the file if it exists other initialise the list
    try:
        replicating_cow = pickle.load(open("cows.p", "rb"))
    except IOError:
        replicating_cow = []

    replicating_cow.append('cow')                         # Add another cow
    print replicating_cow                                 # Print the list       
    pickle.dump(replicating_cow, open("cows.p", "wb"))    # Save the list to disk

if __name__ == "__main__":
    main()

每次跑步后,我们都会得到一头新牛:

$ python replicate_cow.py 
['cow']

$ python replicate_cow.py 
['cow', 'cow']

$ python replicate_cow.py 
['cow', 'cow', 'cow']

$ python replicate_cow.py 
['cow', 'cow', 'cow', 'cow']
相关问题