Python的open方法用来打开一个文件。第一个参数是文件的位置和文件名,第二个参数是读写模式。这里我们采用w模式,也就是写模式。在这种模式下,文件原有的内容将会被删除。
#to write‘,‘
在open的时候制定‘a‘即为(append)模式,在这种模式下,文件的原有内容不会消失,新写入的内容会自动被添加到文件的末尾。
#to append在open的时候制定‘r‘即为读取模式,使用
#to read使用Python的pickle模块,可以将Python对象直接存储在文件中,并且可以再以后需要的时候重新恢复到内容中。
testFile = open(‘pickle.txt‘,‘w‘)调用open函数的时候,在模式的字符串中使用添加一个b即为二进制模式。
#binary mode读取二进制文件。
testFile = open(‘cainiao.txt‘,‘rb‘)
file_object = open(‘thefile.txt‘)
try:
all_the_text = file_object.read(
)
finally:
file_object.close( )
input = open(‘data‘, ‘r‘)
#第二个参数默认为r
input = open(‘data‘)
input = open(‘data‘, ‘rb‘)
file_object = open(‘thefile.txt‘)
try:
all_the_text = file_object.read(
)
finally:
file_object.close( )
file_object = open(‘abinfile‘, ‘rb‘)
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
list_of_all_the_lines = file_object.readlines(
)
for line in file_object:
process line
output = open(‘data‘, ‘w‘)
output = open(‘data‘, ‘wb‘)
output = open(‘data‘, ‘w ‘)
file_object = open(‘thefile.txt‘, ‘w‘)
file_object.write(all_the_text)
file_object.close( )
file_object.writelines(list_of_text_strings)a. Python 2.3 中新增
http://www.360doc.com/content/14/0425/12/16044571_372066859.shtml
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/taoshengyijiuzt/article/details/47067753