开发者社区> 问答> 正文

python怎么转换格式

python怎么转换格式

展开
收起
云计算小粉 2018-05-10 20:10:53 1364 0
1 条回答
写回答
取消 提交回答
  • 最方便的语言,最简洁的简介

    检测源码格式,如果不是utf8,则进行转换,否则跳过
    import chardet
    import sys
    import codecs

    def findEncoding(s):

    file = open(s, mode='rb')
    buf = file.read()
    result = chardet.detect(buf)
    file.close()
    return result['encoding']
    

    def convertEncoding(s):

    encoding = findEncoding(s)
    if encoding != 'utf-8' and encoding != 'ascii':
        print("convert %s%s to utf-8" % (s, encoding))
        contents = ''
        with codecs.open(s, "r", encoding) as sourceFile:
            contents = sourceFile.read()
    
        with codecs.open(s, "w", "utf-8") as targetFile:
            targetFile.write(contents)
    
    else:
        print("%s encoding is %s ,there is no need to convert" % (s, encoding))
    

    if name == "__main__":

    if len(sys.argv) != 2:
        print("error filename")
    else:
        convertEncoding(sys.argv[1])

    实际测试,可以成功转换。

    知识点
    chardet,这个模块是用来检测编码格式的。检测完成之后返回一个dict类型。dict的key又两个,一个是encode,一个是confidence,参数函数顾名思义。
    with as 这个语法很好用,特别是在打开文件的时候,可以处理忘记关闭文件导致文件一直被占用等异常。

    2019-07-17 22:23:20
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载