使用Python按字节分割字符串
发布网友
发布时间:2022-04-24 03:08
我来回答
共1个回答
热心网友
时间:2022-04-06 05:19
按行读取之后按原文件编码类型解码,插入完后按UTF-8解码写入文件
以源文件为gbk为例,假设每5字符插入|
python2
with open('target','w') as f:
for line open('source').readlines():
line=line.decode('gbk')
line='|'.join([line[i:min(i+5,len(line))] for i in range(0,len(line),5)])
f.write(line.encode('utf-8'))
python3
with open('target','w',encoding='utf-8') as f:
for line open('source',encoding='gbk').readlines():
line=line
line='|'.join([line[i:min(i+5,len(line))] for i in range(0,len(line),5)])
f.write(line)