Writing a list to a file with Python

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

    In General

    Following is the syntax for writelines() method

    fileObject.writelines( sequence )
    

    Example

    #!/usr/bin/python
    
    # Open a file
    fo = open("foo.txt", "rw+")
    seq = ["This is 6th line\n", "This is 7th line"]
    
    # Write sequence of lines at the end of the file.
    line = fo.writelines( seq )
    
    # Close opend file
    fo.close()
    

    Reference

    http://www.tutorialspoint.com/python/file_writelines.htm

提交回复
热议问题