day09:文件处理(打开模式,读写方法,指针移动,文件修改)

今日内容:
字符编码:
文件处理的打开模式:
控制文件读写操作的模式:
控制文件读写内容的模式:
文件读写方法
控制文件指针的移动
文件修改的2种方法
 
 
一、字符编码应用:
运行python程序的三个步骤: python test.py
1、启动python解释器
2、解释器将test.py的内容从硬盘读入内存
3、解释器解释执行刚刚读入内存的代码,识别python语法,比如x = "上"
 
二、bytes类型:
编码 编码
字符-------------------->unicode------------->其他编码
 
解码 解码
字符<--------------------unicode<-------------其他编码
 
 
x = "上"
print(x)
res = x.encode("gbk")
print(type(res))
print(res)
print(res.decode("gbk"))
强调:在python3里,只会将unicode格式的数字转成字符,其余编码格式的数字均不会转换
 
三、文件处理
 
1)控制文件读写操作的模式
 
  1、r:只读(默认):
    当文件不存在时,报错(不可读)
    当文件存在时,文件指针跳到文件最开始位置
    风险:把所有内容读入内存,当文件过大,有风险
    推荐使用for line in f:
 
读入的时候,自动换行是因为文件中有回车,而print跟着\n会再自动换一行
所以一共是两行,\n虽然你看不到,但是存在
所以,正确输入是user_list = line.strip('\n').split(':')
 
  2、w:只写:
    当文件不存在时会创建空文件,
    当文件存在时,w会清空文件,文件指针在最开始位置
 
ps:
a、在以w模式打开文件没有关闭的情况下,连续输入,新的内容总是跟在旧的之后
with open('a.txt',mode='wt',encoding='utf-8') as f:
  f.write('平安夜1\n')
  f.write('平安夜2\n')
  f.write('平安夜3\n')
  ———————》
  平安夜1
  平安夜2
  平安夜3
 
b、如果重新以w模式打开文件,会清空文件内容:
with open('a.txt',mode='wt',encoding='utf-8') as f:
  f.write('平安夜1\n')
  f.write('平安夜2\n')
  f.write('平安夜3\n')
  ————————》
  平安夜3
 
   3、a:只追加写
    当文件不存在时,创建新文件
    当文件存在时,文件指针跳到末尾
    with open('a.txt',mode='at',encoding='utf-8') as f:
      f.write('头头大1\n')
      f.write('头头大2\n')
      f.write('头头大3\n')
     
   4、+模式的使用(了解)
    读写模式:一般使用场景中都是纯净模式
    + 模式的使用(了解)
    r+t:可读可写,以r模式为基准
    w+t:
    a+t:
 
 
2)控制文件读写内容的模式:
  t模式的使用:控制读写的内容都是字符串类型,只适用于文本文件,自动编码和解码
  必须要指定encoding参数
  b模式的使用:控制读写的内容都是Bytes类型
  必须不要指定encoding参数
 
 
四、操作文件读写的方法(重点)
  读操作
  f.read:读取所有内容,执行完成后,文件指针会跳到文件末尾
  f.readline:读取一行内容,执行完成后,文件指针会跳到第二行首
  f.readlines:读取每一行内容,存放于列表中
 
 
  写操作:
  f.write('1111\n222\n'):针对文本模式的写,需要自己写换行符
  f.write('1111\n222\n'):针对B模式的写,需要自己写换行符
  f.writelines(['333\n','444\n']):文件模式
  f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]):b模式
 
with open('a.txt',mode='wt',encoding='utf-8') as f:
f.write("1111\n222\n333\n")
 
with open('a.txt',mode='wt',encoding='utf-8') as f:
lines = ['aaaaa\n',"abbbb\n","acccc\n"]
for line in lines:
f.write(line)
 
with open('a.txt',mode='wt',encoding='utf-8') as f:
lines = ['aaaaa\n',"abbbb\n","acccc\n"]
for line in lines:
f.writelines(line)
f.writelines("hello")
 
了解
f.flush():立刻将文件内容从内存刷到硬盘
 
五 、控制文件的指针的移动:
被动:
只有在t模式下的read(n)的n代表的是字符个数,除此以外都是字节个数
1、with open('a.txt',mode='rt',encoding='utf-8') as f:
res = f.read(6)
print(res)
 
2、with open('a.txt',mode='rb') as f:
res = f.read(8)
print(res.decode('utf-8'))
 
3、f.truncate() :截断
with open('a.txt',mode='at',encoding='utf-8') as f:
f.truncate(3)
 
 
主动:
f.seek(移动的字节个数)
 
模式有3种:
0:永远参照文件开头
1:参照当前所在位置
2:永远参照文件末尾
 
ps:
只有0模式在t模式下可以使用,1和2模式只能在b下使用
with open('a.txt',mode='rt',encoding='utf-8') as f:
f.seek(3,0)
f.seek(5,0)
print(f.tell()) ----》5
 
with open('a.txt',mode='rb') as f:
f.seek(3,1)
f.seek(5,1)
print(f.tell())-----》8
 
with open('a.txt',mode='rb') as f:
f.seek(-3,2)
print(f.tell())
f.seek(0,2)
print(f.tell())
 
练习:动态监测文件的最后一行加入的内容
(soft一边在access.log加入,tail一边监测)
soft文件:
import time
# m = time.strftime('%Y-%m-%d %H:%d:%s')
with open('access.log', mode='at', encoding='utf-8') as f:
f.write("%s %s\n" %(time.strftime('%Y-%m-%d %H:%M:%S'), "seven给了你10个亿"))
 
Tail文件:
import time
 
with open('access.log', mode='rb')as f:
f.seek(0, 2)
 
while True:
line = f.readline()
if len(line) == 0:
time.sleep(0.1)
else:
print(line.decode('utf-8'), end='')
 
六、文件的修改
修改文件的两种方法:
方法一:耗内存,不耗硬盘
1、先将文件内容全部读入内存
2、在内存修改内容
3、将修改的内容覆盖回硬盘中的原文件
 
with open('a.txt',mode='rt',encoding='utf-8')as f:
data = f.read()
with open('a.txt',mode='wt',encoding='utf-8')as f1:
f1.write(data.replace('jay','JAY'))
 
方法二:耗硬盘,不耗内存
1、以读的方式打开原文件,以写的方式打开一个临时文件
2、读入原文件的一行内容到内存,然后在内存中修改完毕后写入临时文件,循环往复直到全部 改完
3、删除原文件,重命名临时文件为原文件名
 
import os
with open('a.txt',mode='rt',encoding='utf-8')as src_f, open('.a.txt.swp',mode='wt',encoding='utf-8')as dst_f:
for line in src_f:
dst_f.write(line.replace('JAY','seven'))
os.remove('a.txt')
os.rename('.a.txt.swp','a.txt')

posted @ 2020-12-26 10:01  Seven_1130  阅读(194)  评论(0)    收藏  举报