python3-基础4

字符编码

字符编码:  就是把人类的字符翻译成计算机能识别的数字

字符编码表:  就是一张字符与数字对应关系表   ascii   gbk   utf-8   unicode 

     unicode  ------>  encode(utf-8) ------> bytes  转换     (内存中的编码转换成硬盘的编码,编码)

      bytes ------> decode('utf-8') ------> unicode  转换     (解码)

原则:  字符以什么格式编译的,就要以什么格式解码

  python3 中的字符串分为两种

     x='lalala' 存成 unicode
     y=x.encode('utf-8') 存成 bytes

文件处理

打开文件

f = open('a.txt' , 'r' , encoding = 'utf-8')       #windos下用 GBK编码,Linux下用utf-8编码 

#在r模式下,如果文件不存在,不会创建新文件

res = f.read()    #读取a.txr,光标移动到文件末尾

print(res)

print('第二次' , f.read())     # 光标已经移动到末尾,所以无法再读出文件

print(f.readline() , end='')   #逐行读取,以空格结尾

print(f.readlines())  #读取文件所有行,组成一个列表

f.close()   #  切记关闭已打开的文件

傻瓜式操作  打开--关闭文件   用  with ---  as

with   open('a.txt' , 'r' , encoding = 'utf-8')  as f:      #  用 with  open 打开文件,将结果传给 f, 也可以打开多个文件   open b as f1 , open c as f2 :

    pass

写模式

f=open('a.txt' , 'w' , encoding = 'utf-8' )

f.write('11111111\n')

f.write('2222\n')

f.write('3333\n444444\n')

f.writelines(['a\n' , 'b\n' ,'c\n'])    #

f.close()

 1 #将文件整个读取到内存后,再执行后续操作
 2 with open('old.txt', 'r', encoding='utf-8') as read_f :
 3     msg = read_f.read()
 4     msg = msg.replace('alex', lalala')   #内容替换  Alex 换成  lalala
 5     print(msg)
 6     
 7 with open('old.txt', 'r', encoding='utf-8') as read_f \                     
 8 open('.old.txt.swap', 'w', encoding='utf-8') as write_f :               
 9     msg = read_f.read()
10     msg = msg.replace('alex', lalala')         #内容替换 Alex 换成 lalala
11     print(msg)    
12     write_f.write(msg) 
13 
14 os.remove('old.txt')
15 os.rename('.old.txt.swap', 'old.txt')
16                       
17 #如果文件过大,需要逐行读取
18 import os
19 with open('old.txt', 'r', encoding='utf-8') as read_f \                     
20 open('.old.txt.swap', 'w', encoding='utf-8') as write_f :
21     for line in read_f:   #逐行读取
22         print(line)
23         if 'lalala' in line:   #判断是否有 lalala
24              line = line.replace('lalala', 'alex') #将 lalala 替换为  Alex  
25              write_f.write(line)   #将修改后的内行写入到新的文件里去
26         else:
27              write_f.write(line)   #没有修改的行,也要写入到新的文件里去  
28 os.remove('old.txt')
29 os.rename('.old.txt.swap', 'old.txt')                
30       
 

 几种模式

# r 文本模式的 读 (不能写,只能读),若文件不存在,不会创建新文件

f = open('a.txt', 'r', encoding = 'utf-8')

print(f.read())

f.clos()  #向操作系统请求关闭打开的文件,f为一个变量,

# w 文本模式的 写 (不能读,只能写), 若文件不存在,则创建,若文件存在,则清空

f = open('a.txt', 'w', encoding = 'utf-8')

print(f.writable())     #判断是否为写模式    返回结果 True  或 False

print(f.write())  

f.write('哈哈哈哈\n')

f.writelines(['1111\n','222\n'])

# a 文本模式的追加写入(不能读,只能写)  , 文件存在,则光标跳到文件末尾,若文件不存在,则创建

 f = open('a.txt','a',encoding='utf-8')

 print(f.tell())   #可以返回光标所在位置

 f.write('3333\n')
 f.write('44444\n')

# r+,w+,a+     可读可写模式

#rb 模式 直接从硬盘中读取 bytes

 f = open('a.txt','rb')

 print(f.read())    #出现硬盘保存的文件,人类无法识别

# wb模式 , 若文件存在,会清空
# f=open('a.txt','wb')
# f.write('你好啊'.encode('utf-8'))  #如果不加encode 类型, 会报错

 # ab模式  同 wb模式

# with 模式     --  自动关闭打开的文件

 with open('file.txt','w',encoding='utf-8') as f:
 f.write('1111\n')

拷贝不同格式的文件

 f=open('test.jpg','rb')
 print(f.read())

 with open('test.jpg','rb') as read_f,open('test1.jpg','wb') as write_f:
     # write_f.write(read_f.read())
     for line in read_f:
     write_f.write(line)

 1 #拷贝小程序,名称为 copy.py    -----  python3 copy.py source.file target.file
 2 import sys
 3 #print(sys.argv())  #查看有什么参数
 4 
 5 #python3 copy.py source.file target.file    #需要三个参数:文件本身、源文件、目标文件
 6 if len(sys.argv) < 3:   #若参数小于3  则退出
 7     print('Usage:python3 copy.py source.file target.file')
 8     sys.exit()
 9 
10 
11 #此方法可能导致在不同的平台,文件路径中有不同的符号,导致路径出错
12 # with open(sys.argv[1], 'rb') as read_f, open(sys.argv[2] , 'wb') as write_f :  
13 #     for lin in read_f:
14 #         write_f.write(line)
15 
16 #r'C:\Users\Administrator\test.jpg'   #加r 表示原生字符串,保障路径不会有问题
17 
18 #用下面的方法,保障所有平台可用
19 with open(r'%s' %sys.argv[1],'rb') as read_f,\
20         open(r'%s' %sys.argv[2],'wb') as write_f:
21 
22     for line in read_f:
23         write_f.write(line)

文件其他操作

f=open('a.txt','r',encoding='utf-8')   #读取文本
print(f.read(3))  #可以读取三个字符,中文算一个,英文也算一个

 f=open('a.txt','rb')   #以字节方式读取
 print(f.read(3).decode('utf-8'))  #读了三个字节,一个中文占用3个字节,decode解码后显示一个汉字

 print(f.read(6).decode('utf-8'))   #读取两个汉字

一: read(3):

  1. 文件打开方式为文本模式时,代表读取3个字符

  2. 文件打开方式为b模式时,代表读取3个字节

二: 其余的文件内光标移动都是以字节为单位如seek,tell,truncate

注意:

  1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

  2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果

 f=open('a.txt','rb')     #字节模式下
 print(f.read(3))    #读取三个字节(一个中文)
 print(f.tell())    #查看光标的位置  
 f.seek(3)     #以文件开头作为参照物,相当于 f.seek(3, 0 ),光标移动到第三个字节的位置

 f.seek(3,1)       #以文件当前的光标位置作为参照物,光标移动到当前光标往后数3个字节的位置

 f.seek(3,2)       #以文件结尾作为参照物,光标移动到倒数第三个字节的位置

 print(f.tell())    #查看光标的位置
 print(f.read().decode('utf-8'))   #解码,显示文本信息

 1 # python3 tail.py -f access.log    
 2 #检测某个文件的更新,比如 access.log
 3 
 4 import time
 5 import sys    #调用argw,是个列表,里面的参数为   脚本名称 , -f参数 , 文件名称 
 6 
 7 with open(r'%s' % sys.argv[2], 'rb') as f:    #打开文件,该文件必须存在,下标为2的参数为文件名称
 8     f.seek(0, 2)  #光标移动到文件最末尾
 9 
10     while True:
11         line = f.readline()   #整行读取
12         if line:
13             print(line.decode('utf-8'),end='')   ##将文本解码,以空格为结尾
14         else:
15             time.sleep(0.2)   #等待0.2秒再次执行
16             
17             
18 #自动添加文件内容            
19 # with open('acess.log','a') as f:
20 #     f.write('1111\n')            
21              

截断文件,属于写模式

 with open('a.txt','r+',encoding='utf-8') as f:
 f.truncate(2)    #以文件开头为参照物,截取前两个字节,之后的文件清空,如果是中文,必须截取3的倍数的字符,否则会乱码

猜你喜欢

转载自www.cnblogs.com/Albert-w/p/10711095.html