Writing a list to a file with Python

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

    Using Python 3 and Python 2.6+ syntax:

    with open(filepath, 'w') as file_handler:
        for item in the_list:
            file_handler.write("{}\n".format(item))
    

    This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

    Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".

提交回复
热议问题