要读取文件名,当文件名含有中文名时如何处理?
将中文文件名写进txt没问题:
path = 'C:/Users/liesmars/Desktop/视频/'
with open('try.txt','a') as f:
f.write(path)
f.close()
但是当要获取该文件夹下的文件就会出错,含有中文找不到该路径。
(1)用listdir
# -*- coding: utf-8 -*-
import os
uipath = 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编码转为中文
本文介绍了解决Python中处理含有中文的文件路径问题的方法。通过使用`unicode`转换路径字符串,并结合`os.listdir`及`os.walk`遍历目录,成功实现了对中文文件名的正确读取。

1401

被折叠的 条评论
为什么被折叠?



