convert.py 1.6 KB

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