1.字符编码
(1)ASCII码:
二进制字符串
每一个二进制(bit)有0,1两种状态
每8个二进制有256种状态,称为字节(byte)。
(2)GB2312:
简体中文使用GB2312,两个字节表示一个汉字。
(3)Unicode码:
对每一个符号进行编码,又称为抽象编码
传输编码由UTF规定,有UTF-8,UTF-16
(4)UTF码:
例如UTF-8码,以8位(1B)表示英语字符,以24位(3B)表示中文及其他字符。
2.文件读写
python根据文件编码方式不同将文件分为两类:文本文件和二进制文件。
(1)文件读取:
文本文件的读取:read(),readline(),readlines()
按行读取:
#按行读取:
fd = open(filename,"r")
while True:
line = fd.readline()
if line:
print(line)
else:
break
fd.close()
多行读取:
#多行读取:
fd = open(filename,"r")
lines = fd.readlines()
for line in lines:
print(line)
fd.close()
一次读取:
#一次性读取:
fd = open(filename,"r")
content = fd.read()
print(content)
fd.close()
读取前几位字符:
#读取前几位字符:
fd = open(filename,"r")
print('length:',fd.tell()) #读取当前读写指针
fd.seek(0) #返回文件开头
content = fd.read(5) #读取前5个字节
print(content)
fd.close()
(2)文件写入:
文件写入有两种方式:write(),writelines()
字符串写入:
#字符串写入:
fd = open(filename,"w+") #写入方式,清除原来内容
fd.write('hello\n')
fd.close()
列表写入:
#列表写入:
fd = open(filename,"a+") #追加方式
content = ['hello\n','how are you\n']
fd.writelines(content)
fd.close()