将列表写入文件并将其读入

时间:2014-03-05 05:55:16

标签: python

我有以下代码,将该列表写入文件并以列表格式原样读回的最佳方法是什么。任何帮助将不胜感激。

l=[
            "[ 'ARAJunkyard_Build_Branch' , 7 , 6 , 1 ]",
            "[ 'ARAJunkyard_Build_Head' , 10 , 10 , 0 ]",
            "[ 'ARAJunkyard_DevUnitTests_Branch' , 10 , 9 , 1 ]",
            "[ 'ARAJunkyard_DevUnitTests_HEAD' , 10 , 0 , 10 ]",
            "[ 'ARAJunkyard_Functional_Tests' , 7 , 2 , 5 ]"]

1 个答案:

答案 0 :(得分:1)

只需使用pickle模块,您就可以使用pickle存储几乎所有对象:

import pickle

l=[
            "[ 'ARAJunkyard_Build_Branch' , 7 , 6 , 1 ]",
            "[ 'ARAJunkyard_Build_Head' , 10 , 10 , 0 ]",
            "[ 'ARAJunkyard_DevUnitTests_Branch' , 10 , 9 , 1 ]",
            "[ 'ARAJunkyard_DevUnitTests_HEAD' , 10 , 0 , 10 ]",
            "[ 'ARAJunkyard_Functional_Tests' , 7 , 2 , 5 ]"]

with open("test.dat", "wb") as fp:
    pickle.dump(l, fp)


with open("test.dat", "rb") as fp:
    l2 = pickle.load(fp)

print l2

http://docs.python.org/2/library/pickle.html