python 读取中文路径

来源:互联网 发布:哪个论坛源码好 编辑:程序博客网 时间:2024/05/18 02:39

要读取文件名,当文件名含有中文名时如何处理?

将中文文件名写进txt没问题:


path = 'C:/Users/liesmars/Desktop/视频/'with open('try.txt','a') as f:f.write(path)f.close()

但是当要获取该文件夹下的文件就会出错,含有中文找不到该路径。

(1)用listdir

# -*- coding: utf-8 -*-import osuipath = unicode(path,'utf-8')filelist = os.listdir(uipath)for files in filelist:print files.encode('utf-8')



(2)os.walk


path1 = 'C:/Users/liesmars/Desktop/视频/'uipath1 = unicode(path1,'utf-8')for root,dirs,files, in os.walk(uipath1):for filename in files:filename = filename.encode('utf-8')root = root.encode('utf-8')filepath = os.path.join(root,filename)print 'filepath:',filepath

结果:

filepath: C:/Users/liesmars/Desktop/视频/无人机视频2.mp4
filepath: C:/Users/liesmars/Desktop/视频/视屏2\无人机拍摄视频.mp4

编码的问题还要再仔细看看。

unicode将中文转为计算机可以理解的语言

encode将unicode编码转为中文


                                             
0 0
原创粉丝点击