self-confidence,the source of all the power

导航

python编码

 

在使用python做一些简单实用的工具时,经常会处理一些不是英文的字符,比如遍历中文路径,处理一些日文印度文等的字串时,解析器往往报一些编译不了的错,或打印一些乱码出来,这就是需要用到编码器了。

1
2
3
4
5
6
7
8
9
import os
 
def a():
    cwd = os.getcwd()
    for root,dirs, files in os.walk(r'd:\\资料'):
        print('root, dirs, files : %s : %s : %s'%(root, dirs, files))
 
if __name__ == '__main__':
    a()

  一般情况下,上述代码是运行不了的,那是因为他根本识别不了中文路径,让它能顺利执行,可以通过下面两种方法解决

1.  文件第一行标明编码方式:#coding=utf-8

2. code as below

1
2
3
4
5
def a():
    cwd = os.getcwd()
    d = unicode(r'd:\\资料', 'utf8'# use utf8 decode string
    for root,dirs, files in os.walk(d):
        print('root, dirs, files : %s : %s : %s'%(root, dirs, files))

  

posted on   漩涡鸣人  阅读(815)  评论(0编辑  收藏  举报

努力加载评论中...
点击右上角即可分享
微信分享提示