Python 3.11文件把UTF-8编码转换成ANSI/ASCII/GB2312/GBK编码,完整可执行脚本,可自定义,解决问题

import os,codecs,sys,time,win32con,win32api
if len(sys.argv)==1:sys.exit()
for filename in sys.argv[1:]:
 if not os.path.isfile(filename):continue
 f=codecs.open(filename,'r','utf8')
 utfstr=f.read();f=open(filename+"a",'wb')
 f.write(utfstr.encode('mbcs'));f.close()
os.remove(filename);os.rename(filename+"a",filename)
# win32api.SetFileAttributes(filename,win32con.FILE_ATTRIBUTE_HIDDEN)

如果想把文件都输出为隐藏文件,可以取消最后一行的注释
然后再运行脚本
运行方法:
0. 需要已经安装Python
1.复制此代码,粘贴到一个后缀名.py的文件里
2. 拖动文件到此文件上,即可


如何把这个写成Sublime Text插件:

import sublime
import sublime_plugin
import os
import codecs
import subprocess

class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("save")
        for region in self.view.sel():
            filename = self.view.file_name()
            with codecs.open(filename, 'r', 'utf-8') as f:
                utfstr = f.read()
            with open(filename + "a", 'wb') as f:
                try:
                    f.write(utfstr.encode('mbcs'))
                except:
                    f.write(utfstr.encode('gb2312'))
                    sublime.active_window().run_command("revert")
            print("Save and encode plugin activated!")
        self._cleanup_file(filename)

    def _cleanup_file(self, filename):
        os.remove(filename)
        os.rename(filename + "a", filename)
        subprocess.call(["attrib", "+H", filename])
        sublime.active_window().run_command("revert")
        sublime.status_message("File encoded and original deleted.")


把这个命名为utf-8togbk.py,然后放到UTF-8toGBK文件夹,把文件夹放到sublime text\Data\Packages目录中,然后重启sublime text

然后在首选项快捷键设置中写入:
[ { "keys": ["ctrl+s"], "command": "example"} ]
如果已经有中括号了,就只复制这里中括号内的

现在,搭配ConverttoUTF8插件使用,非常好

可以实现打开GB2312 (GBK/ANSI)后编辑,和保存成GB2312编码

猜你喜欢

转载自blog.csdn.net/LingLing1301/article/details/130251396
今日推荐