Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a list to a file with Python

Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?

file.writelines(["%s\n" % item  for item in list]) 

It seems like there would be a standard way...

like image 718
Josh Arenberg Avatar asked May 22 '09 17:05

Josh Arenberg


People also ask

How do I write a list to a file in a list Python?

A loop is used to iterate over the list items, and the write() method is used to write list items to the file. We use the open() method to open the destination file. The mode of opening the file shall be w that stands for write . Both of the codes will result in writing a list to a file with Python.

How do you write a list of numbers in a file in Python?

A common approach to write the elements of a list to a file using Python is to first loop through the elements of the list using a for loop. Then use a file object to write every element of the list to a file as part of each loop iteration. The file object needs to be opened in write mode.


1 Answers

You can use a loop:

with open('your_file.txt', 'w') as f:     for item in my_list:         f.write("%s\n" % item) 

In Python 2, you can also use

with open('your_file.txt', 'w') as f:     for item in my_list:         print >> f, item 

If you're keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

like image 55
Alex Martelli Avatar answered Sep 19 '22 07:09

Alex Martelli