pythonスクリプトwindows下のファイルgbk符号化とutf-8相互変換を実現

5404 ワード

コードは次のとおりです.
import codecs
import sys
def ReadFile(filePath, encoding="utf-8"):
    with codecs.open(filePath, "r", encoding) as f:
        return f.read()


def WriteFile(filePath, u, encoding="gbk"):
    with codecs.open(filePath, "w", encoding) as f:
        f.write(u)


def UTF8_2_GBK(src, dst, reverse = False):
    if reverse == False:
        content = ReadFile(src, encoding="utf-8")
        WriteFile(dst, content, encoding="gbk")
    else:
        content = ReadFile(src, encoding="gbk")
        WriteFile(dst, content, encoding="utf-8")


if __name__ == "__main__":
    if len(sys.argv) == 2:
        UTF8_2_GBK(sys.argv[1], sys.argv[1])
    else:
        UTF8_2_GBK(sys.argv[1], sys.argv[1], True)