Writing a list to a file with Python

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

    The simpler way is:

    with open("outfile", "w") as outfile:
        outfile.write("\n".join(itemlist))
    

    You could ensure that all items in item list are strings using a generator expression:

    with open("outfile", "w") as outfile:
        outfile.write("\n".join(str(item) for item in itemlist))
    

    Remember that all itemlist list need to be in memory, so, take care about the memory consumption.

提交回复
热议问题