学习笔记 | 如何转换文本文件的编码格式

文摘   2024-08-20 08:00   北京  

学习笔记 | 如何转换文本文件的编码格式

前言

游戏不打先,还要写代码

当我将本地写好的 python 代码上传到服务器,准备运行时给我报错编码不对

令人忍不住大喊一声气死偶咧

原因查明为我代码的编码是 GBK,LINUX 服务器要求的是 UTF-8

那么除了重写一份代码,还有其他选择吗

python 代码转换编码

首先,我们需要一个可以读取和写入不同编码格式的函数。这里使用 Python 内置的 open 函数,它允许我们指定文件打开的模式以及编码格式。
其次,调用 sys 的 argv 进行传递参数方便直接使用脚本

import sys
import codecs

def convert_encoding(input_filename, output_filename, from_encoding, to_encoding):
    with codecs.open(input_filename, 'r', from_encoding) as input_file:
        with codecs.open(output_filename, 'w', to_encoding) as output_file:
            output_file.write(input_file.read())

if __name__ == "__main__":
    if len(sys.argv) != 5:
        print("Usage: python convert_encoding.py <input_file> <output_file> <from_encoding> <to_encoding>")
        sys.exit(1)

    input_filename = sys.argv[1]
    output_filename = sys.argv[2]
    from_encoding = sys.argv[3]
    to_encoding = sys.argv[4]

    convert_encoding(input_filename, output_filename, from_encoding, to_encoding)

使用方式如下

!python convert_encoding.py abc.py abc_utf8.py gbk utf-8

linux 命令语句

在类 Unix 系统(如 Linux 或 macOS)中,你可以使用 iconv 命令行工具来转换文件的编码。iconv 是一个非常强大的工具,可以用来转换各种文件编码。

!iconv -f GBK -t UTF-8 input_file.gbk > output_file.utf8

小结

通过 Python 或 Linux 命令行工具,我们可以轻松地解决由编码格式不一致带来的问题。无论是批量转换还是单个文件处理,掌握这些技巧都能帮助我们避免编码带来的困扰,让我们的代码在任何平台上都能顺利运行。
当然我更推荐 linux 的命令,更加简单


气python风雨
主要发一些涉及大气科学的Python文章与个人学习备忘录
 最新文章