convert.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Python3 将GBK转换成utf-8编码,明天继续实现,把*.java文件 *.porperties文件都转成utf-8
  2. import os
  3. import chardet
  4. import codecs
  5. def WriteFile(filePath, u, encoding="utf-8"):
  6. with codecs.open(filePath, "w", encoding) as f:
  7. f.write(u)
  8. def GBK_2_UTF8(src, dst):
  9. # 检测编码,coding可能检测不到编码,有异常
  10. f = open(src, "rb")
  11. coding = chardet.detect(f.read())["encoding"]
  12. f.close()
  13. if coding != "utf-8":
  14. with codecs.open(src, "r", encoding) as f:
  15. try:
  16. WriteFile(dst, f.read(), coding="utf-8")
  17. try:
  18. print(src + " " + coding + " to utf-8 converted!")
  19. except Exception:
  20. print("print error")
  21. except Exception:
  22. print(src +" "+ coding+ " read error")
  23. # 把目录中的*.java编码由gbk转换为utf-8
  24. def ReadDirectoryFile(rootdir):
  25. for parent, dirnames, filenames in os.walk(rootdir):
  26. for dirname in dirnames:
  27. #递归函数,遍历所有子文件夹
  28. ReadDirectoryFile(dirname)
  29. for filename in filenames:
  30. if filename.endswith(".java"):
  31. GBK_2_UTF8(os.path.join(parent, filename),
  32. os.path.join(parent, filename))
  33. if __name__ == "__main__":
  34. src_path = "D:/liuyuqi/twtech/github/q 前端/java-note/src"
  35. ReadDirectoryFile(src_path)