怎么使用Python批量对文本文件编码互转

其他教程   发布日期:2025年03月04日   浏览次数:148

这篇文章主要介绍“怎么使用Python批量对文本文件编码互转”,在日常操作中,相信很多人在怎么使用Python批量对文本文件编码互转问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么使用Python批量对文本文件编码互转”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

在Windows下写C语言默认是GB2312,放到Linux上就会乱码,因为Linux和MacOS默认是UTF-8,因此写了个Python小脚本对指定路径下的文件进行转换。

  1. from sys import argv
  2. import os
  3. from chardet import detect
  4. from codecs import lookup
  5. CONFIG_FILE = '.any2any'
  6. DEFAULT_CONFIG = '''
  7. .c
  8. .h
  9. .cpp
  10. .hpp
  11. .hxx
  12. .cc
  13. .cxx
  14. .C
  15. .c++
  16. .m
  17. .cs
  18. .rs
  19. .java
  20. .kt
  21. .php
  22. .pm
  23. .pl
  24. .py
  25. .sh
  26. .go
  27. .xml
  28. .htm
  29. .html
  30. .css
  31. .js
  32. .jsx
  33. .vue
  34. .txt
  35. .csv
  36. '''
  37. if os.path.exists(CONFIG_FILE):
  38. with open(CONFIG_FILE, 'r') as config_file:
  39. file_extension = tuple(config_file.read().split())
  40. else:
  41. file_extension = tuple(DEFAULT_CONFIG.split())
  42. print(f"将转换 {' '.join(list(file_extension))}")
  43. def bytes_encoding(b: bytes, length: int = 1024) -> str:
  44. '''
  45. 返回探测到的编码格式
  46. '''
  47. return detect(b[:length])['encoding']
  48. def any2any(b: bytes, encoding: str) -> bytes:
  49. '''
  50. 任意编码字节转换为任意编码字节
  51. 探测输入的字节编码格式,转换为指定编码,并返回对应字节
  52. '''
  53. file_encoding = bytes_encoding(b)
  54. if file_encoding == encoding:
  55. return b
  56. return lookup(encoding).encode(lookup(file_encoding).decode(b)[0])[0]
  57. def allfileset(path: str = '.', filepathset: set = set()) -> set:
  58. '''
  59. 递归路径下所有文件,返回绝对路径集合
  60. '''
  61. if os.path.isdir(path):
  62. for item in os.listdir(path):
  63. filepath = os.path.join(path, item)
  64. if os.path.isfile(filepath):
  65. filepathset.add(os.path.abspath(filepath))
  66. else:
  67. allfileset(filepath, filepathset)
  68. else:
  69. filepathset.add(os.path.abspath(path))
  70. return filepathset
  71. def is_valid_inputs() -> bool:
  72. '''
  73. 检查参数是否输入正确
  74. '''
  75. return len(argv) > 1 and all(map(os.path.exists, argv[1:]))
  76. def is_valid_encoding(encoding: str) -> bool:
  77. '''
  78. 检查是否存在指定编码
  79. '''
  80. try:
  81. lookup(encoding)
  82. return True
  83. except:
  84. return False
  85. def choice_encoding() -> str:
  86. choice = input('''!!!在转换前注意备份文件!!!
  87. 要转换到什么编码?
  88. 1. GB18030(Windows下常用,C语言不会乱码)
  89. 2. UTF-8(非Windows下通用,例如Linux和macOS)
  90. 3. 其他
  91. > ''')
  92. if choice == '1':
  93. return 'GB18030'
  94. elif choice == '2':
  95. return 'UTF-8'
  96. elif choice == '3':
  97. choice = input('输入你想转换到的编码:')
  98. while not is_valid_encoding(choice):
  99. choice = input('不存在该编码,重新输入:')
  100. return choice
  101. else:
  102. print('不做任何操作')
  103. exit()
  104. def main():
  105. if is_valid_inputs():
  106. encoding = choice_encoding()
  107. filepathset = set()
  108. for path in argv[1:]:
  109. filepathset.union(filter(lambda s: s.endswith(file_extension), allfileset(path, filepathset)))
  110. if filepathset:
  111. for path in filepathset:
  112. with open(path, 'rb') as f:
  113. filebytes = any2any(f.read(), encoding)
  114. with open(path, 'wb') as f:
  115. f.write(filebytes)
  116. print(f'{path} 已转换到 {encoding}')
  117. print('转换已完成')
  118. else:
  119. print('没有任何可以转换的文件,请检查程序下是否有.any2any配置文件,用空格或换行间隔要转换的文件类型,例如 .c .cpp .cs')
  120. else:
  121. print("未收到任何要转换的文件或文件夹路径,或参数错误,请把要转换的文件或文件夹拖动到程序上。")
  122. if __name__ == "__main__":
  123. try:
  124. main()
  125. finally:
  126. input('按任意键退出...')

可以使用pyinstaller打包成可执行文件,带着走或者分享给其他人用

安装pyinstaller

  1. conda install pyinstaller

打包Python文件,其中

  1. -i
参数可以给.exe文件加上图标,
  1. -F
参数指定要打包的脚本
  1. pyinstaller -i icon.ico -F any2any.py

最后打包好的可执行文件在dict路径下。

以上就是怎么使用Python批量对文本文件编码互转的详细内容,更多关于怎么使用Python批量对文本文件编码互转的资料请关注九品源码其它相关文章!