Writing a list to a file with Python

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

提交回复
热议问题