Python文件编码---gbk OR utf8

本文探讨了Python中文件编码的选择问题,重点在于Windows环境下处理中文文件名时的编码转换。文章指出,Windows文件名编码为cp936,而Python中可以使用decode('utf-8').encode('cp936')来处理。文中建议,尽管GBK编码包含更多字符,但由于部分软件不支持,推荐使用UTF8编码,因为它在各种浏览器和编辑器中广泛接受。同时,文章提到了Python源代码中定义编码的方法,并介绍了Python处理Unicode编码的演变过程。
摘要由CSDN通过智能技术生成
               

Python文件编码---gbk?OR utf8?

windows文件名的编码是cp936的,你在使用中文文件名的时候转下码就行了。

比如你python文件编码是utf8

# -*- coding: utf-8 -*-

he='开心.mp3'
f=open(he.decode('utf-8').encode('cp936'),'w')
f.close()

-----------------------------------------------
如果是GB2312,则是最佳选择.GB2312含7千多字.GB2312是国内外软件普遍接受和支持的8bit双字节中文编码.

但你是gbk.GBK是扩展的GB2312,大部分软件不支持它.用GBK时,论坛内容显示时,一些非GB2312中文字会显示成空白方块.

utf8好,UTF8是unicode的传送型式.主流浏览器IE和netscape都支持.

[看一下IE的View->Encoding下的可接受编码,看一下netscape的View->Charactercoding下的可接受编码,找得到GB2312和UTF8,找不到GBK!这就是在GBK和UTF8两种编码中只好选UTF8的原因.]

------------------------------------------------
用编码gbk还是utf8
------------------------------------------------
# -*- coding: UTF-8 -*- 这是个注释吗?
这是用来说明你的Python源程序文件用使用的编码。缺省情况下你的程序需要使用ascii码来写,但如果在其中写中文的话,python解释器一般会报错,但如果加上你所用的文件编码,python就会自动处理不再报错。

上述格式还可以写成:

#coding=utf-8

#coding:utf-8
-------------------------------------------------
Defining Python Source Code Encodings

Abstract
    This PEPproposes to introduce a syntax to declare the encoding of
    a Pythonsource file. The encoding information is then used by the
    Pythonparser to interpret the file using the given encoding. Most
    notably thisenhances the interpretation of Unicode literals in
    the sourcecode and makes it possible to write Unicode literals
    using e.g.UTF-8 directly in an Unicode aware editor.

Problem
    In Python2.1, Unicode literals can only be written using the
    Latin-1based encoding "unicode-escape". This makes the
    programmingenvironment rather unfriendly to Python users who live
    and work innon-Latin-1 locales such as many of the Asian
    countries.Programmers can write their 8-bit strings using the
    favoriteencoding, but are bound to the "unicode-escape" encoding
    for Unicodeliterals.

Proposed Solution
    I propose tomake the Python source code encoding both visible and
    changeableon a per-source file basis by using a spe

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值