文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 61.182.251.99 [DateTime(2004-09-20T08:17:12Z)] TableOfContents

描述

写文件

Credit : Luther Blissett

问题

文件中写入文本或2进制数据 ?

解决 Solution

将一个(大)字符串写入文件的最简单的方法如下:

    open('thefile.txt', 'w').write(all_the_text)  # 写入文本到文本文件
    open('abinfile', 'wb').write(all_the_data)    # 写入数据到2进制文件

更好的方法是将文件对象和一个变量绑定,可以及时关闭文件。比如,文本文件写入内容:

    file_object = open('thefile.txt', 'w')
    file_object.write(all_the_text)
    file_object.close(  )

写入文件的内容更多时不是一个大字符串,而是一个字符串的list(或其他序列),这时应该使用writelines方法(此方法同样适用于2进制文件的写操作)

    file_object.writelines(list_of_text_strings)
    open('abinfile', 'wb').writelines(list_of_data_strings)

使用writelines方法, 相对于使用string的join方法产生一个大字符串然后写入文件或者循环调用write方法,运行要快许多。

讨论

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.

   1 

...

参考 See Also