python2.7 编码问题解析(四) open与编码的关系

来源:互联网 发布:数据库中存储的是 编辑:程序博客网 时间:2024/06/18 10:05
import sys, localedef SysCoding():    fmt = '{0}: {1}'    #当前系统所使用的默认字符编码    print fmt.format('DefaultEncoding    ', sys.getdefaultencoding())    #转换Unicode文件名至系统文件名时所用的编码('None'表示使用系统默认编码)    print fmt.format('FileSystemEncoding ', sys.getfilesystemencoding())    #默认的区域设置并返回元祖(语言, 编码)    print fmt.format('DefaultLocale      ', locale.getdefaultlocale())    #用户首选的文本数据编码(猜测结果)    print fmt.format('PreferredEncoding  ', locale.getpreferredencoding())    #解释器Shell标准输入字符编码    print fmt.format('StdinEncoding      ', sys.stdin.encoding)    #解释器Shell标准输出字符编码    print fmt.format('StdoutEncoding     ', sys.stdout.encoding)SysCoding()

(代码来自http://www.cnblogs.com/tester-l/p/6056077.html)

以上代码可以测试系统中有关编码的设定,其中sys.getfilesystemencoding()

这个是和打开文件相关的,我系统给出的文件系统名所用的编码是:FileSystemEncoding : mbcs

实际上在http://www.cnblogs.com/tester-l/p/6056077.html中,人家说的已经很清楚。

在打开文件的时候,文件路径的编码需要和系统相关的。

#-*-coding:utf8-*-dir1 = "测试.txt"#file = open(dir1)dir2 = "测试.txt".decode('utf8')file = open(dir2)print "2" + file.readline()file.close()dir3 = "测试.txt".decode('utf8').encode('mbcs')file = open(dir3)print "3" + file.readline()print [dir2]print [dir3]
两种编码都能正确的打开文件,我觉得还是根据文件系统的编码打开是比较合适的。

windows中代码页和通用编码标准的对应表:

https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx

936gb2312ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312)65001utf-8Unicode (UTF-8)

原创粉丝点击