文章来自《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)
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.
...
讨论 Discussion
参考 See Also