python2.7 編碼問題解析(四) open與編碼的關係

import sys, locale
def 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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章