一、字符编码
- 编码
bytes = '张三'.encode() # encode()自动按utf-8编码
print(bytes)
print(type(bytes))
bytes = '张三'.encode('utf-8')
print(bytes)
print(type(bytes))
bytes = '张三'.encode('gbk')
print(bytes)
print(type(bytes))
输出:
b'xe5xbcxa0xe4xb8x89'
b'xe5xbcxa0xe4xb8x89'
b'xd5xc5xc8xfd'
- 解码
bytes = b'xe5xbcxa0xe4xb8x89'
msg1 = bytes.decode()
print(msg1)
print(type(msg1))
msg1 = bytes.decode('utf-8')
print(msg1)
print(type(msg1))
msg1 = bytes.decode('gbk')
print(msg1)
print(type(msg1))
输出:
张三
张三
寮犱笁
二、文件
1.文件的存储方式
在计算机中,文件是以二进制的方式保存在磁盘上的。
2.文件的操作
打开文件
读、写文件
读:将文件内容读入内存
写:将内存内容写入文件
关闭文件
3.文件打开方式总结
访问方式
说明
r
以只读方式打开文件。文件的指针将会放在文件的开头,这是默认模式。如果文件不存在,抛出异常
w
以只写方式打开文件。如果文件存在会被覆盖。如果文件不存在,创建新文件
a
以追加方式打开文件。如果该文件已存在,文件指针将会放在文件的结尾。如果文件不存在,创建新文件进行写入
r+
以读写方式打开文件。文件的指针将会放在文件的开头。如果文件不存在,抛出异常
w+
以读写方式打开文件。如果文件存在会被覆盖。如果文件不存在,创建新文件
a+
以读写方式打开文件。如果该文件已存在,文件指针将会放在文件的结尾。如果文件不存在,创建新文件进行写入
4.练习
创建文件data.txt, 文件共100000行, 每行存放一个1~100之间的整数. 2). 找出文件中数字出现次数最多的10个数字, 写入文件mostNum.txt;
import random
from collections import Counter
with open('aa.txt','w+') as f:
for i in range(10000):
f.write(str(random.randint(1,100))+'
')
f.seek(0,0)
# print(f.read())
dic1 = {}
with open('aa.txt') as f:
for i in f:
if i not in dic1:
dic1[i] = 1
else:
dic1[i] += 1
print(dic1)
d = Counter(dic1)
with open('bb.txt','w+') as f2:
for i in d.most_common(10):
f2.write(f'{i[0].strip()}-----{i[1]}
')
f2.seek(0,0)
print(f2.read())
1). 编写程序, 将a.txt操作生成文件a_num.txt文件, 2). 其中文件内容与a.txt一致, 但是在每行的行首加上行号。
with open('cc.txt','w+') as f1, open('dd.txt','w+') as f2 :
f1.write('Hello
Welcome
What is the luck...
')
f1.seek(0,0)
for i,j in enumerate(f1):
f2.write(f'{i} {j}')
f2.seek(0,0)
print(f2.read())
读取图片并另存到另一个文件
with open('image.jpg','rb') as f:
temp = f.read()
print(temp)
with open('image2.jpg','wb') as f2:
f2.write(temp)