Tuesday, August 13, 2013

Python - How to write a list to a file?



How to write an entire list of elements into a file? Let us see in this article how to write a list l1 to a file 'f1.txt':

1. Using write method:
#!/usr/bin/python

l1=['hi','hello','welcome']

f=open('f1.txt','w')
for ele in l1:
    f.write(ele+'\n')

f.close()
 The list is iterated, and during every iteration, the write method writes a line to a file along with the newline character.

2. Using string join method:
#!/usr/bin/python

l1=['hi','hello','welcome']

f=open('f1.txt','w')
s1='\n'.join(l1)
f.write(s1)
f.close()
  Using join method, the entire list can be joined using a delimiter and formed into a string. Now, using the write method, the string can be written to the file. In this, only one write method is needed for the entire list.

3. Using string join along with  with open syntax:
#!/usr/bin/python

l1=['hi','hello','welcome']

with open('f1.txt','w') as f:
  f.write('\n'.join(l1))
  The with open syntax automatically closes the file at the end of the block, hence no need of explicit call to the close method. Instead of using a variable to contain the joined string, it is directly given to the write method.

4. Using the writelines method:
#!/usr/bin/python

l1=['hi','hello','welcome']

f=open('f1.txt','w')
l1=map(lambda x:x+'\n', l1)
f.writelines(l1)
f.close()
 Python provides a method, writelines, which is very useful to write lists to a file. write method takes a string as argument, writelines takes a list. writelines method will write all the elements of the list to a file. Since it writes to the file as is, before invoking the writelines method, the list elements should be appended with newline characters, so that the list elements will come in individual lines. This is achieved using the map function which will add a newline to every list element.

3 comments:

  1. writelines() takes any iterable, if you do

    f.writelines("hello")

    The result will be a file:
    h
    e
    l
    l
    o

    ReplyDelete
  2. "ele+'\n'" just begs for TypeError: can only concatenate list (not "str") to list

    ReplyDelete