Python中中文路徑處理問題的研究,
a = '你' 為 str 對象
a = u'你' 為 unicode 對象
1.
>>> print 'u' + '你'
>>> u浣
輸出亂碼
2.
>>> print 'u' + u'你'
>>> u你
正常
3.
>>> print 'u你'
>>> u浣
輸出亂碼
4.
>>> print 'u你' + 'u'
>>> u浣爑
輸出亂碼
5.
>>> print u'u你' + 'u'
>>> u你u
正常
6.
>>> print u'u你' + '你'
出現錯誤 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
分析:'你'在記憶體中 為 0xe4,而python預設的編碼方案是ascii,ascii無法識別0xe4
7.
>>> print u'u你' + u'你'
>>> u你你
正常
8.
>>> print 'u你' + u'你'
出現錯誤 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 1: ordinal not in range(128)
9.
>>> print 'u你'.decode('utf-8') + u'你'
>>> u你你
正常
10.
而在處理由系統採集的含有中文的路徑時,使用string.decode('utf-8')就不一定行了,因為簡體中文的windows系統預設編碼為gb2312,繁體中文版會採用Big5碼
實驗過程如下:
file_from = sys.argv[1] 為由系統採集的包含中文的路徑
file_to = file_from[:file_from.rfind('\\')+1].decode('utf-8') + u'你_' + file_from[file_from.rfind('\\')+1:].decode('utf-8')
print file_to
將出現錯誤:UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 24: invalid start byte
應該使用:decode('gb2312')
file_to = file_from[:file_from.rfind('\\')+1].decode('gb2312') + u'你_' + file_from[file_from.rfind('\\')+1:].decode('gb2312')
print file_to 正常
11.
而如果file_from是由你自己寫入的包含中文的路徑,如file_from = ‘c:\你.txt’
那麼就應該用decode('utf-8')
可以參考上面的第7點和第9點
不足及錯誤之處,請批評指正!!謝謝!!
參考文章:
Why you benefit from using UTF-8 Unicode everywhere in your web applicationsPython "'ascii' codec can't decode byte" explained and how to solve it
Windows 記事本的 ANSI、Unicode、UTF-8 這三種編碼模式有什麼區別?