数学建模社区-数学中国
标题:
转换文件编码
[打印本页]
作者:
2744557306
时间:
2024-3-31 17:14
标题:
转换文件编码
示例为把
gb2312
编码的文件转化为utf8编码。
def conv(file:str):
6 s- X: q2 M9 b1 ~/ a
s=""
: l5 A! o& }- M/ w3 y2 v1 p. r
try:
1 w3 I. M/ d1 W$ n) B
with open(file,encoding="gb2312") as f:
. S$ s7 {$ ] N/ ^) S. [% \
s=f.read()
Y5 d) x* j2 D" W, {
os.remove(file)
3 z* S1 P- P% Z8 a" q
with open(file,mode="w+",encoding="utf-8") as f:
7 U6 H/ d# G$ f- ^
f.write(s)
# O) C. v1 h* a, D1 } J
except Exception as e:
1 k4 t c, ~8 ]+ F9 ~ ?0 [
print("conv failed",file)
2 o) B" ~0 E* T0 ?
! p5 e& R1 `2 C( @* o2 @
复制代码
; G" ^$ i" X; g6 r* R
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/)
Powered by Discuz! X2.5