Writing a list to a file with Python

后端 未结 21 1793
孤街浪徒
孤街浪徒 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:13

    This logic will first convert the items in list to string(str). Sometimes the list contains a tuple like

    alist = [(i12,tiger), 
    (113,lion)]
    

    This logic will write to file each tuple in a new line. We can later use eval while loading each tuple when reading the file:

    outfile = open('outfile.txt', 'w') # open a file in write mode
    for item in list_to_persistence:    # iterate over the list items
       outfile.write(str(item) + '\n') # write to the file
    outfile.close()   # close the file 
    

提交回复
热议问题