open()函数用于打开一个文件,并返回文件对象,在对文件的处理过程中都会用到这个函数,如果该文件无法被打开,会抛出OSError。在使用的过程中要保证关闭文件对象,即调用close()函数。
语法格式:
我们可以查看帮助手册
>>> help(open)
Help on built-in function open in module io:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
参数含义:
file:必须,文件路径(相对或绝对路径)
mode:可选,文件打开模式
buffering:设置缓冲
encoding:一般使用utf8
errors:报错级别
newline:区分换行符
closed:传入的file参数类型
mode的参数有:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
默认是文本模式,如果要以二进制方式打开的话,加上b。
以上参数也可以放在一起使用~
还有对 这几种模式的总结:
举个例子哈~
>>> open("d:\\xixi.txt",mode='w+') #我这个文件本来是不存在的
#通过w创建后,返回的是file文件对象的相关信息
<_io.TextIOWrapper name='d:\\xixi.txt' mode='w+' encoding='cp936'>
>>> f = open("d:\\xixi.txt",mode='r') #赋值给f,使用read()读出文件内容
>>> f.read()
'嘻嘻'
file文件对象的属性:
file.closed 返回true如果文件已被关闭,否则返回false。
file.mode 返回被打开文件的访问模式。
file.name 返回文件的名称。
>>> fo = open("d:\\xixi.txt")
>>> print(fo.name) #文件名称
d:\xixi.txt
>>> print(fo.closed) #文件是否关闭
False
>>> fo.close() #关闭文件
>>> print(fo.closed)
True
>>> print(fo.mode) #文件的打开模式
r
file对象
file对象是使用open()方法来创建的,以下列举file对象常用的几个函数~
close()方法是用来关闭打开的文件的
read()方法是用来读取文件中的数据的
write()方法是用来向文件中写数据的
tell()方法是告诉你当前指针的位置的
#write()
>>> fo = open("d:\\xixi.txt",'a+')
>>> fo.write("\n欢迎来到‘溪仔的阿宝呀’的博客~")
17
>>> fo.close()
#read()
>>> fr = open("d:\\xixi.txt","r+")
>>> fr.read()
'嘻嘻\n欢迎来到‘溪仔的阿宝呀’的博客~'
>>> fr.close()
#tell()
#当我们向文件里读或写的时候,指针会跟着向后指,我们来看一下获取位置和重定位到文件开始
>>> ft = open("d:\\xixi.txt","r+")
>>> ft.read(10) #读取十个长度
'嘻嘻\n欢迎来到‘溪仔'
>>> ft.tell() #查看当前指针位置
20 #一个汉字占两个字节,大家可以换成英文试一下
>>> ft.seek(0,0) #重置指针位置至文件开始
0
>>> ft.read(10) #重新读文件
'嘻嘻\n欢迎来到‘溪仔'
>>> ft.read(10) #可以看见继续读的话,指针会一直向后走
'的阿宝呀’的博客~'
>>> ft.close()
嘻嘻~
写完啦