数学建模社区-数学中国

标题: 转换文件编码 [打印本页]

作者: 2744557306    时间: 2024-3-31 17:14
标题: 转换文件编码
示例为把gb2312编码的文件转化为utf8编码。
  1. def conv(file:str):6 s- X: q2 M9 b1 ~/ a
  2.     s=""
    : l5 A! o& }- M/ w3 y2 v1 p. r
  3.     try:1 w3 I. M/ d1 W$ n) B
  4.         with open(file,encoding="gb2312") as f:
    . S$ s7 {$ ]  N/ ^) S. [% \
  5.             s=f.read()  Y5 d) x* j2 D" W, {
  6.         os.remove(file)3 z* S1 P- P% Z8 a" q
  7.         with open(file,mode="w+",encoding="utf-8") as f:7 U6 H/ d# G$ f- ^
  8.             f.write(s)# O) C. v1 h* a, D1 }  J
  9.     except Exception as e:
    1 k4 t  c, ~8 ]+ F9 ~  ?0 [
  10.         print("conv failed",file)
    2 o) B" ~0 E* T0 ?

  11. ! p5 e& R1 `2 C( @* o2 @
复制代码

; G" ^$ i" X; g6 r* R




欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5