Writing a list to a file with Python

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

    You can use a loop:

    with open('your_file.txt', 'w') as f:
        for item in my_list:
            f.write("%s\n" % item)
    

    In Python 2, you can also use

    with open('your_file.txt', 'w') as f:
        for item in my_list:
            print >> f, item
    

    If you're keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

提交回复
热议问题