如何表示字符
map 65 -> a 66 ->b :ASCII 一个字符占:8 bit 2 ** 8 = 256 ==》127
GB2312 # GBK
Unicode 编码 16 2 ** 16:等长编码
UTF-8 变长编码
bytes = '张三'.encode("GBK")
print(bytes)
print(type(bytes))
byte_utf8 = '张三'.encode("utf-8")
print(byte_utf8)
str1 = bytes.decode("GBK")
print(str1)
str1 = byte_utf8.decode("GBK")
print(str1)
文件操作
文本文件 二进制文件
文本文件本质上存储时,也是二进制。但可以用文本编辑器查看。
二进制文件,无法通过文本编辑器查看。
try:
f = open("D://demo.txt",'w',encoding="utf-8")
f.write("neuedu\n")
f.write('NEUQ')
f.write("一片两片123")
finally:
f.close()
# help(open)
with open("D://demo.txt",'a',encoding="utf-8") as ff:
ff.write("neuedu\n")
ff.write('NEUQ')
ff.write("一片两片")
# help(open)
with open("D://demo.txt",encoding="utf-8") as f:
# content = f.read()
# print(content)
# line = f.readline()
# while line:
# print(line)
# line = f.readline()
for line in f.readlines():
print(line)
print("----------------")
with open("D://demo.txt",encoding="utf-8") as f:
print(f.tell())
print(f.read())
# whence: 0:文件的开头 1:当前指针所在位置 2 :文件的末尾
f.seek(0,0)
print(f.tell())
print(f.read())
文件的打开模式:
r:以只读方式打开文件。文件的指针会放在文件的开头。这是默认模式。如果文件不存在,抛出异常。
w:以只写方式打开文件。如果文件存在会被覆盖。如果文件不存在,会创建文件。
a:以追加方式打开文件。如果文件已存在,则指针会放在文件的结尾。如果文件不存在,则创建新文件。
r+: 以读写方式打开文件。文件的指针放在文件的开头。如果文件不存在,则抛出异常。
w+: 以读写方式打开文件。如果文件存在,会被覆盖。如果不存在,则创建文件。
a+: 以读写方式打开文件。如果存在,则指针在文件的末尾。如果不存在,则创建文件。
with open("D://1200.jpg",'rb') as f:
lines = f.read()
with open("D://12001.jpg", 'wb') as f1:
f1.write(lines)
作业:
(1)创建文件:data.txt,一共100000行,每行存放一个1-100之间的整数。
(2)找出文件中数字出现最多的10个数字。写入到文件:mostNum.txt中。
collections.Counter
from collections import Counter
count_list = Counter(['B','A','B','A','B','B','A','B','B','C'])
print(count_list)
print(count_list.most_common(2))
count_truple = Counter((1,2,3,1,1,1,2,1,3,3))
print(count_truple)
import random
with open("data.txt",'w+') as f:
for i in range(100000):
num = random.randint(1,101);
f.write(str(num)+ "\n")
with open("data.txt","r+") as f:
lists = []
line = f.readline()
while line:
lists.append(line)
line = f.readline()
print(Counter(lists).most_common(10))
#chmod