Writing a list to a file with Python

后端 未结 21 1815
孤街浪徒
孤街浪徒 2020-11-22 01:48

Is this the cleanest way to write a list to a file, since writelines() doesn\'t insert newline characters?

file.writelines([\"%s\\n\" % item  fo         


        
21条回答
  •  心在旅途
    2020-11-22 02:25

    What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?

    If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.

    import pickle
    
    with open('outfile', 'wb') as fp:
        pickle.dump(itemlist, fp)
    

    To read it back:

    with open ('outfile', 'rb') as fp:
        itemlist = pickle.load(fp)
    

提交回复
热议问题