注:Python版本为3.5.2
函数open():
函数功能:打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作。
f=open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
函数的参数说明:
1、file:
表示需要打开文件的相对路径(当前工作目录)或者一个绝对路径,当传入路径不存在此文件会报错。或者传入文件句柄(file descriptor)。
>>> a = open('test.txt') # 相对路径
>>> a
<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp936'>
>>> a.close()
>>> a = open(r'D:\Python\Python35-32\test.txt') # 绝对路径
>>> a
<_io.TextIOWrapper name='D:\\Python\\Python35-32\\test.txt' mode='r' encoding='cp936'>
脚本:
f=open("D:\\Users\\2.txt","rt",encoding="utf-8",newline="\r\n")
a=f.fileno() #获取文件句柄
print(a)
d=open(a,closefd=False,encoding="utf-8")
print(d)
执行结果:
3
<_io.TextIOWrapper name=3 mode='r' encoding='utf-8'>
文件
2、mode:
Python中文件默认为读方式打开
f=open(url,'r',encoding='utf-8')
其他打开方式:
官方说明:
'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)
常见的mode组合:
'r'或'rt': 默认模式,文本读模式
'w'或'wt': 以文本写模式打开(打开前文件会被清空)
'rb': 以二进制读模式打开
'ab': 以二进制追加模式打开
'wb': 以二进制写模式打开(打开前文件会被清空)
'r+': 以文本读写模式打开,可以写到文件任何位置;默认写的指针开始指在文件开头, 因此会覆写文件
'w+': 以文本读写模式打开(打开前文件会被清空)。可以使用read*()
'a+': 以文本读写模式打开(写只能写在文件末尾)。可以使用read*()
'rb+': 以二进制读写模式打开
'wb+': 以二进制读写模式打开(打开前文件会被清空)
'ab+': 以二进制读写模式打开
例子:
f=open(url,'w')
写模式,创建一个文件,可以写入数据,原内容会被覆盖。
f=open(url,'a'):
追加模式,在文件末尾追加数据,不能读取。
f=open(url,'b'):
二进制模式
3、buffering:
用来设置数据量缓冲大小
有参数情况下规则:
0:只允许在二进制模式下,关闭缓冲。
1:在文本模式下,正行缓冲
>1:固定大小的缓冲
无参数情况下的规则(默认规则):
1、二进制文件为固定大小的缓冲,大小依赖于设备的块大小(block siez)和io.DEFAULT_BUFFER_SIZE。在许多的系统上,大小为4096或8192 bytes。
2、文本文件:如果是设备终端文件(即isatty() 返回True),是整行作为缓冲。其他的遵循上面的规则。
4、encoding:
用来指定编码或解码的字符集,只用于文本文档。默认值为None,即用操作系统编码:
f=open(url,encoding='utf-8')
5、errors:
表示读写文件时碰到错误的报错级别。
常见的报错基本有:
•'strict' 严格级别,字符编码有报错即抛出异常,也是默认的级别,errors参数值传入None按此级别处理.
•'ignore' 忽略级别,字符编码有错,忽略掉.
•'replace' 替换级别,字符编码有错的,替换成?.
文件:2.txt文件
编码:utf-8
内容:飞行
脚本1:
f=open("2.txt","rt")
print(f.readline())
f.close()
执行结果:
Traceback (most recent call last):
File "D:/Users/demo8.py", line 2, in <module>
print(f.readline())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa1 in position 4: illegal multibyte sequence
脚本2:
f=open("2.txt","rt",encoding="utf-8")
print(f.readline())
f.close()
执行结果:
飞行
脚本3:
f=open("2.txt","rt",errors='ignore')
print(f.readline())
f.close()
执行结果:
椋炶
脚本3:
f=open("2.txt","rt",errors='replace')
print(f.readline())
f.close()
执行结果:
椋炶��
6、newline:
只适用于文本模式,用于控制文件换行。可选的值:None , ”“ , ‘\n’ , ‘\r’ 和’\r\n’。
输入:
如果值为None,换行符\n', '\r'或'\r\n',都会转换成\n处理。
如果是"",则不做任何转换。
如果是其他值,则会按照设定的参数值返回换行符。
输出:
如果值为None,换行符\n都会转成对应的系统默认换行符(os.linesep)。
如果值为""或\n,则不做任何转换。
如果是其他值,换行符\n转换成对应的参数值。
示例:
文件内容:
飞行
你好
默认值:
>>> f=open("D:\\Users\\2.txt","rt",encoding="utf-8")
>>> f.readline()
'飞行\n'
>>> f.close()
设置参数值为\r\n:
>>> f=open("D:\\Users\\2.txt","rt",encoding="utf-8",newline="\r\n")
>>> f.readline()
'飞行\r\n'
>>> f.close()
7、closefd:
表示传入的file参数类型(缺省为True),传入文件路径时一定为True,传入文件句柄则默认为False,如果为False,在文件关闭时文件句柄不会关闭。
>>> a = open('test.txt','rt',encoding = 'utf-8',newline = '\n',closefd = False)
Traceback (most recent call last):
File "<pyshell#115>", line 1, in <module>
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)
脚本:
f=open("D:\\Users\\2.txt","rt",encoding="utf-8",newline="\r\n")
a=f.fileno()
print(a)
d=open(a,closefd=False,encoding="utf-8")
print(d)
d.close()
d=open(a,closefd=True,encoding="utf-8")
print(d)
d.close()
d=open(a,closefd=False,encoding="utf-8")
print(d)
d.close()
执行结果:
3
<_io.TextIOWrapper name=3 mode='r' encoding='utf-8'>
<_io.TextIOWrapper name=3 mode='r' encoding='utf-8'>
Traceback (most recent call last):
File "D:/Users/HUANGZHIWEI816/PycharmProjects/moon/demo8.py", line 10, in <module>
d=open(a,closefd=False,encoding="utf-8")
OSError: [WinError 6] 句柄无效。
文件操作:
方法一:需要close()关闭文件流
f=open("2.txt","r")
for line in f: #一行一行读,f是一个迭代器
pass
f.close()
方法二:不用close()关闭文件流
with open("2.txt","r") as f:
for line in f:
pass
常用属性:
1、file.encoding:
文件编码
2、file.name
文件名
常用方法:
1、file.close()
关闭文件流,关闭后文件不能再进行读写操作,会报异常:ValueError: I/O operation on closed file。
脚本:
f=open("2.txt","rt")
print(f.readline())
f.close()
print(f.readline())
执行结果:
飞行
Traceback (most recent call last):
File "demo8.py", line 4, in <module>
print(f.readline())
ValueError: I/O operation on closed file
2、file.read([size]):
从文件读取指定的字节数,如果未给定或为负则读取所有。
脚本:
f=open("2.txt","rt")
result=f.read()
print(result)
f.close()
执行结果:
飞行
你好
哈哈哈哈
3、file.readline([size])
不指定参数,读取整行,包括 “\n” 字符。
指定参数,返回指定参数大小(bytes)的数据。如参数大小超过整行的字节数,则返回整行。
脚本:
f=open("2.txt","rt")
result=f.readline()
print(result)
f.close()
执行结果:
飞行
4、file.readlines([sizehint])
读取所有行并返回列表,若给定sizeint>0,则是设置一次读多少字节,这是为了减轻读取压力。
脚本:
f=open("2.txt","rt",encoding="utf-8")
result=f.readlines()
print(result)
f.close()
执行结果:
['飞行\n', '你好\n', '哈哈哈哈']
5、file.write(str):
将字符串写入文件,没有返回值。
f=open("2.txt","wt",encoding="utf-8")
f.write("snow")
f.close()
6、file.flush()
正常先到缓冲区,缓冲区满了,写入硬盘。flush()会刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
import time
f=open("2.txt","wt",encoding="utf-8")
f.write("snow")
f.flush()
time.sleep(10)
f.close()
这里使用flush会立刻将”snow”写入文件中,而不是等10s之后文件要关闭前写入文件。
7、file.tell():
返回文件指针当前位置。单位:字节数
文件内容:
你好
snow
脚本内容:
f=open("2.txt","r",encoding="utf-8")
print(f.tell())
f.readline()
print(f.tell())
f.readline()
print(f.tell())
f.close()
执行结果:
0
8
14
8、file.seek(offset, whence=io.SEEK_SET)
设置文件指针的位置,参数offset为移动的位置
f=open("2.txt","r",encoding="utf-8")
f.readline()
print(f.tell())
f.seek(3)
print(f.tell())
f.close()
执行结果:
8
3
9、file.isatty()
如果文件连接到一个终端设备返回 True,否则返回 False。
10、file.fileno()
返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。
>>> f=open(r"2.txt","r")
>>> f.fileno()
3