Python 3 字符和文件读写

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值