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.