[Python]打开文件的模式

Python中以sys.open()方法打开文件

1 import sys
2 
3 file = open("D:\\file.txt")

 

其中可在第二个参数的位置指定打开文件的模式

1 import sys
2 
3 file = open("D:\\file.txt", "r")

 

参数共有以下几种:

rU或Ua 以读方式打开,同时提供通用换行符支持(PEP278)
wb 以写方式打开,
a 以追加模式打开(从EOF开始,必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开(参见w)
a+ 以读写模式打开(参见a)
rb 以二进制读模式打开
wb 以二进制写模式打开(参见w)
ab 以二进制追加模式打开(参见a)
rb+ 以二进制读写模式打开(参见r+)
wb+ 以二进制读写模式打开(参见w+)
ab+ 以二进制读写模式打开(参见a+)

 

下面对一些常用模式(r+, w+, a+)稍作测试: 

r+:

在对应文件不存在时:

1 file = open("D:\\file.txt", "r+")

 

导致IO错误

IOError: [Errno 2] No such file or directory: 'D:\\file.txt'

 

在对应文件存在时:

1 import sys
2 
3 sys.stdout = open("D:\\file.txt", "r+")
4 print "this is second line"

将导致原文件内容被擦除,变为:

this is second line

 

w+:

在对应文件不存在时:

1 import sys
2 
3 sys.stdout = open("D:\\file.txt", "w+")
4 print "this is second line"

将创建新文件file.txt并写入内容

 

在对应文件存在时:

上述代码将导致原文件内容被擦除,变为:

this is second line

 

a+:

在对应文件不存在时:

1 import sys
2 
3 sys.stdout = open("D:\\file.txt", "a+")
4 print "this is second line"

将创建新文件file.txt并写入内容

 

在对应文件存在时:

上述代码将会把内容写入文件末尾,文件内容变为:

this is first line
this is second line

 

综上,各模式功能总结如下:

  创建文件 覆盖 or 添加
r+ 覆盖
w+ 覆盖
a+ 添加

posted on 2014-07-21 15:07  shelven  阅读(710)  评论(0编辑  收藏  举报

导航