Credit: Luther Blissett
Here is the most convenient way towrite one big string to a file:
open('thefile.txt', 'w').write(all_the_text) # text to a text fileopen('abinfile', 'wb').write(all_the_data) # data to a binary file
However, it is better to bind thefile object to a variable so that you cancall close
on it as soon asyou’re done. For example, for a text file:
file_object = open('thefile.txt', 'w')file_object.write(all_the_text)file_object.close( )
More often, the data you want to write is not in one big string butin a list (or other sequence) of strings. In this case, you shoulduse thewritelines
method (which, despite its name, is not limited to lines and worksjust as well with binary data as with text files):
file_object.writelines(list_of_text_strings)open('abinfile', 'wb').writelines(list_of_data_strings)
Calling writelines
is much faster than eitherjoining the strings into one big string (e.g., with''.join
) and then callingwrite
, or calling write
repeatedly in a loop.
To create a file object for writing, you must always pass a secondargument toopen
—either'w'
to write textual data, or'wb'
to write binary data. The same considerationsillustrated in Recipe 4.2 also apply here,except that calling close
explicitly is even moreadvisable when you’re writing to a file rather thanreading from it. Only by closing the file can you be reasonably surethat the data is actually on the disk and not in some temporarybuffer in memory.
Writing a file a little at a time is more common and less of aproblem than reading a file a little at a time. You can just callwrite
and/or writelines
repeatedly, as each string or sequence of strings to write becomesready. Each write operation appends data at the end of the file,after all the previously written data. When you’redone, call the close
method on the file object. Ifyou have all the data available at once, a singlewritelines
call is faster and simpler. However, ifthe data becomes available a little at a time, it’sat least as easy and fast to call write
as itcomes as it would be to build up a temporary list of pieces (e.g.,with append
) to be able to write it all at once inthe end with writelines
. Reading and writing arequite different from each other, with respect to the performanceimplications of operating in bulk versus operating a little at atime.
Recipe 4.2; documentation for theopen
built-in function and file objects in theLibrary Reference.
Get Python Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.