说明:
1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作。
2. file参数表示的需要打开文件的相对路径(当前工作目录)或者一个绝对路径,当传入路径不存在此文件会报错。或者传入文件的句柄。
>>> a = open(‘test.txt‘) # 相对路径
>>> a
>>> a.close()
>>> a = open(r‘D:\Python\Python35-32\test.txt‘) # 绝对路径
>>> a
3. mode参数表示打开文件的模式,常见的打开模式有如下几种,实际调用的时候可以根据情况进行组合。
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
r ,只读模式【默认】
w,只写模式【不可读;不存在则创建;存在则清空内容;】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
x+ ,写读【可读,可写】
a+, 写读【可读,可写】
"b"表示以字节的方式操作
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
# t为文本读写,b为二进制读写
>>> a = open(‘test.txt‘,‘rt‘)
>>> a.read()
‘some text‘
>>> a = open(‘test.txt‘,‘rb‘)
>>> a.read()
b‘some text‘
# r为只读,不能写入;w为只写,不能读取
>>> a = open(‘test.txt‘,‘rt‘)
>>> a.write(‘more text‘)
Traceback (most recent call last):
File "", line 1, in
a.write(‘more text‘)
io.UnsupportedOperation: write
>>> a = open(‘test.txt‘,‘wt‘)
>>> a.read()
Traceback (most recent call last):
File "", line 1, in
a.read()
io.UnsupportedOperation: not readable
#其它不一一举例了
4. buffering表示文件在读取操作时使用的缓冲策略。
0: 代表buffer关闭(只适用于二进制模式)
1: 代表line buffer(只适用于文本模式)
>1: 表示初始化的buffer大小
5. encoding参数表示读写文件时所使用的的文件编码格式。
假设现在test.txt文件以utf-8编码存储了一下文本:
>>> a = open(‘test.txt‘,‘rt‘) # 未正确指定编码,有可能报错
>>> a.read()
Traceback (most recent call last):
File "", line 1, in
a.read()
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 8: illegal multibyte sequence
>>> a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘)
>>> a.read()
‘我是第1行文本,我将被显示在屏幕\n我是第2行文本,我将被显示在屏幕\n我是第3行文本,我将被显示在屏幕‘
>>>
6. errors参数表示读写文件时碰到错误的报错级别。
常见的报错基本有:
‘strict‘ 严格级别,字符编码有报错即抛出异常,也是默认的级别,errors参数值传入None按此级别处理.
‘ignore‘ 忽略级别,字符编码有错,忽略掉.
‘replace‘ 替换级别,字符编码有错的,替换成?.
>>> a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘)
>>> a.read()
‘我是第1行文本,我将被显示在屏幕\n我是第2行文本,我将被显示在屏幕\n我是第3行文本,我将被显示在屏幕‘
>>> a = open(‘test.txt‘,‘rt‘)
>>> a.read()
Traceback (most recent call last):
File "", line 1, in
a.read()
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 8: illegal multibyte sequence
>>> a = open(‘test.txt‘,‘rt‘,errors = ‘ignore‘ )
>>> a.read()
>>> a = open(‘test.txt‘,‘rt‘,errors = ‘replace‘ )
>>> a.read()
7. newline表示用于区分换行符(只对文本模式有效,可以取的值有None,‘\n‘,‘\r‘,‘‘,‘\r\n‘)
>>> a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘,newline = ‘\r‘)
>>> a.readline()
‘我是第1行文本,我将被显示在屏幕\r‘
>>> a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘,newline = ‘\n‘)
>>> a.readline()
‘我是第1行文本,我将被显示在屏幕\r\n‘
8. closefd表示传入的file参数类型(缺省为True),传入文件路径时一定为True,传入文件句柄则为False。
>>> a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘,newline = ‘\n‘,closefd = False)
Traceback (most recent call last):
File "", line 1, in
a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘,newline = ‘\n‘,closefd = False)
ValueError: Cannot use closefd=False with file name
>>> a = open(‘test.txt‘,‘rt‘,encoding = ‘utf-8‘,newline = ‘\n‘,closefd = True)
原文:http://www.cnblogs.com/ITPower/p/7121849.html