Python中中文路徑處理問題的研究,

來源:互聯網
上載者:User

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 這三種編碼模式有什麼區別?





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.