Writing a list to a file with Python

后端 未结 21 1786
孤街浪徒
孤街浪徒 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:08
    file.write('\n'.join(list))
    
    0 讨论(0)
  • Why don't you try

    file.write(str(list))
    
    0 讨论(0)
  • 2020-11-22 02:11
    poem = '''\
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
    use Python!
    '''
    f = open('poem.txt', 'w') # open for 'w'riting
    f.write(poem) # write text to file
    f.close() # close the file
    

    How It Works: First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a ’t’ext file and opens it in ’r’ead mode. In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.

    The above example is from the book "A Byte of Python" by Swaroop C H. swaroopch.com

    0 讨论(0)
  • 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".

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题