2007-07-05
Python Cookbook 2.2 文件写操作
需求:
要写文本或者二进制数据到一个文件里.
讨论:
这里有一个很简单的方法,一次写一个长字符串到文件中:
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
然而,最好是绑定一个文件对象,这样你在操作完的时候可以关闭它,比如:
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
很懂情况下,要写的数据不是一个字符串,而是一系列字符串,在这种情况下,可以使用writelines方法(和名字所表达的含义不同,它不仅仅支持文本字符串):
file_object.writelines(list_of_text_strings)
open('abinfile', 'wb').writelines(list_of_data_strings)
调用writelines方法要比循环调用write方法或者将若干字符串拼接后调用write方法要快很多.
创建一个文件对象用于写操作的时候,要给open方法传递第二个参数,'w'或者'wb',和上一节相同,建议使用异常处理,因为写操作比读操作更需要关闭文件,否则会出现文件内容的丢失,因为只有close了,文件内容才能保证在硬盘上,而不是内存中.
一次写一部分数据到文件,比一次从文件读一部分数据更常见.你可以通过循环调用write或writelines来实现这个需求,数据每次添加到文件的末尾,最后你再调用close方法来关闭文件.如果数据都是准备好的 ,调用一次writelines要比循环调用write更快;如果数据是一次来一点,使用write方法比较好,而不是缓存到内存中(比如使用append方法),最后一次调用writelines.读操作和写操作是完全不同的,对于写操作,一次写一点比一次写一大块要更方便一些.
当你使用'w'或者'wb'参数打开文件时,文件原先的内容立刻消失了.即使你打开它后立刻关闭,数据依然不存在了.如果你希望写操作添加数据到原先的文件末尾 ,可以使用'a'或者'ab'参数,还有更多的允许同时读和写操作的参数如'r+b',是高级参数中最常用的.
相关说明:
write(...)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
writelines(...)
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
要写文本或者二进制数据到一个文件里.
讨论:
这里有一个很简单的方法,一次写一个长字符串到文件中:
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
然而,最好是绑定一个文件对象,这样你在操作完的时候可以关闭它,比如:
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
很懂情况下,要写的数据不是一个字符串,而是一系列字符串,在这种情况下,可以使用writelines方法(和名字所表达的含义不同,它不仅仅支持文本字符串):
file_object.writelines(list_of_text_strings)
open('abinfile', 'wb').writelines(list_of_data_strings)
调用writelines方法要比循环调用write方法或者将若干字符串拼接后调用write方法要快很多.
创建一个文件对象用于写操作的时候,要给open方法传递第二个参数,'w'或者'wb',和上一节相同,建议使用异常处理,因为写操作比读操作更需要关闭文件,否则会出现文件内容的丢失,因为只有close了,文件内容才能保证在硬盘上,而不是内存中.
一次写一部分数据到文件,比一次从文件读一部分数据更常见.你可以通过循环调用write或writelines来实现这个需求,数据每次添加到文件的末尾,最后你再调用close方法来关闭文件.如果数据都是准备好的 ,调用一次writelines要比循环调用write更快;如果数据是一次来一点,使用write方法比较好,而不是缓存到内存中(比如使用append方法),最后一次调用writelines.读操作和写操作是完全不同的,对于写操作,一次写一点比一次写一大块要更方便一些.
当你使用'w'或者'wb'参数打开文件时,文件原先的内容立刻消失了.即使你打开它后立刻关闭,数据依然不存在了.如果你希望写操作添加数据到原先的文件末尾 ,可以使用'a'或者'ab'参数,还有更多的允许同时读和写操作的参数如'r+b',是高级参数中最常用的.
相关说明:
write(...)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
writelines(...)
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.