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...
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.
What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?
If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.
import pickle
with open('outfile', 'wb') as fp:
pickle.dump(itemlist, fp)
To read it back:
with open ('outfile', 'rb') as fp:
itemlist = pickle.load(fp)
The simpler way is:
with open("outfile", "w") as outfile:
outfile.write("\n".join(itemlist))
You could ensure that all items in item list are strings using a generator expression:
with open("outfile", "w") as outfile:
outfile.write("\n".join(str(item) for item in itemlist))
Remember that all itemlist
list need to be in memory, so, take care about the memory consumption.
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"
.
Yet another way. Serialize to json using simplejson (included as json in python 2.6):
>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()
If you examine output.txt:
[1, 2, 3, 4]
This is useful because the syntax is pythonic, it's human readable, and it can be read by other programs in other languages.