import os
# path 文件路径
# name 文件名
def read(path, name):
with open(path + os.sep + name, 'rb') as f: # 字节读取方便更换解码方式
# for i in range(100):
while True:
lines = f.readlines(100) # 大文件每次读取100行提高性能
if not lines:
break
for line in lines:
# 尝试解码(一般不会遇到一个文件以不同的编码格式写入,这里只是提供一个思路)
try:
line = line.decode("GB18030")
# print(line)
except UnicodeDecodeError as e:
print(e)
try:
line = line.decode("utf-8")
print(line)
except UnicodeDecodeError as e:
print(e)
continue
print(line)
# 处理内容
f.close()
python文件读取(中途可更换编码)
最新推荐文章于 2022-11-27 15:54:24 发布