I l@ve RuBoard Previous Section Next Section

4.3 Writing to a File

Credit: Luther Blissett

4.3.1 Problem

You want to write text or data to a file.

4.3.2 Solution

Here is the most convenient way to write one big string to a file:

open('thefile.txt', 'w').write(all_the_text)  # text to a text file
open('abinfile', 'wb').write(all_the_data)    # data to a binary file

However, it is better to bind the file object to a variable so that you can call close on it as soon as you'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 but in a list (or other sequence) of strings. In this case, you should use the writelines method (which, despite its name, is not limited to lines and works just 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 either joining the strings into one big string (e.g., with ''.join) and then calling write, or calling write repeatedly in a loop.

4.3.3 Discussion

To create a file object for writing, you must always pass a second argument to open梕ither 'w' to write textual data, or 'wb' to write binary data. The same considerations illustrated in Recipe 4.2 also apply here, except that calling close explicitly is even more advisable when you're writing to a file rather than reading from it. Only by closing the file can you be reasonably sure that the data is actually on the disk and not in some temporary buffer in memory.

Writing a file a little at a time is more common and less of a problem than reading a file a little at a time. You can just call write and/or writelines repeatedly, as each string or sequence of strings to write becomes ready. Each write operation appends data at the end of the file, after all the previously written data. When you're done, call the close method on the file object. If you have all the data available at once, a single writelines call is faster and simpler. However, if the data becomes available a little at a time, it's at least as easy and fast to call write as it comes 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 in the end with writelines. Reading and writing are quite different from each other, with respect to the performance implications of operating in bulk versus operating a little at a time.

4.3.4 See Also

Recipe 4.2; documentation for the open built-in function and file objects in the Library Reference.

    I l@ve RuBoard Previous Section Next Section