一、文件的读取
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
- file: 必需,文件路径(相对或者绝对路径)。
- mode: 可选,文件打开模式
- buffering: 设置缓冲
- encoding: 一般使用utf8
- errors: 报错级别
- newline: 区分换行符
- closefd: 传入的file参数类型
- opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。
常用方法:
1、f.read():读取文件的所有数据,默认从头开始,读取出来的数据类型为字符串
2、f.readline():读取第一行数据,更省内存
3、f.readlines():按行读取所有文件的数据,返回list, 每一行就是list的一个元素 换行符也会读取出来
# f.read()
f = open(file=r'D:\python\day09\test01.txt', mode='r', encoding='UTF-8')
res = f.read()
print(type(res)) # 读取数据的类型
print(res)
f.close()
# f.redline()
f = open(file=r'D:\python\day09\test01.txt', mode='r', encoding='UTF-8')
res = f.readline()
print(type(res)) # 读取数据的类型
print(res)
f.close()
# f.readlines()
f = open(file=r'D:\python\day09\test01.txt', mode='r', encoding='UTF-8')
res = f.readlines()
print(type(res)) # 读取数据的类型
print(res)
f.close()
二、写文件
1、f.write('python39期20210413') 覆盖写入文件
2、f.writelines(data) 覆盖写入
写入的时候不会换行,所有数据都会写在同一行(遇到换行符才会换行)
#f.write()
f = open(file=r'D:\python\day09\test01.txt', mode='w', encoding='UTF-8')
res = f.write('123456789')
print(res)
f.close()
# f.writelines( )
f = open(file=r'D:\python\day09\test01.txt', mode='w', encoding='UTF-8')
res = f.writelines('123456\n456789')
f.close()
三、mode参数
r:只读文件
w:只写文件(覆盖)
a:只写文件(追加写入)--append
+:
r+:可以读&可以写(覆盖)
w+:可以读&可以写(覆盖)
a+:可以读&可以写(追加写入)
rb:二进制形式读取(图片)
wb:二进制形式写入(图片)
ab:二进制形式追加写入(图片)
四、光标操作
seek(0)
offset:偏移量(字节数)
whence:默认是0,从哪里开始偏移
0:从文件开头开始算起
1:从光标当前位置开始算起
2:从文件末尾开始算起
# 文件的保存,seek光标
f=open(file=r'D:\python\day09\test01.txt',mode='a+',encoding='UTF-8')
result = f.write('hello python')
f.seek(0)
read_result= f.read()
print(read_result)
f.close()
五、文件保存
f.flush()
1、写文件的时候都是往内存区域里面去写,等程序运行结束之后,就会从内存区写到你的文件
2、f.flush()将内存里的缓冲区域的文件写入到文件保存
3、使用场景:大量写入数据的时候,建议一边写一边保存,防止数据丢失
import time
f=open(file=r'D:\python\day09\test01.txt',mode='a+',encoding='UTF-8')
num = 0
while num <30:
time.sleep(1)
print('test')
f.write('hello python\n')
num += 1
f.flush()
f.close()