浅谈Python2获取中文文件名的编码问题,浅谈python2
浅谈Python2获取中文文件名的编码问题,浅谈python2
问题:
Python2获取包含中文的文件名是如果不转码会出现乱码。
这里假设要测试的文件夹名为test,文件夹下有5个文件名包含中文的文件分别为:
Python性能分析与优化.pdf
Python数据分析与挖掘实战.pdf
Python编程实战:运用设计模式、并发和程序库创建高质量程序.pdf
流畅的Python.pdf
编写高质量Python代码的59个有效方法.pdf
我们先不转码直接打印获取到的文件名,代码如下:
import os for file in os.listdir('./test'): print(file)
输出乱码:
Python���ܷ������Ż�.pdf Python���ݷ������ھ�ʵս.pdf Python���ʵս���������ģʽ�������ͳ���ⴴ������������.pdf ������Python.pdf ��д������Python�����59����Ч����.pdf
解决:
先测试一下文件名的编码,这里我们用到chardet模块,安装命令:
pip install chardet
用chardet.detect函数检测一下文件名的编码方式:
{'confidence': 0.99, 'encoding': 'GB2312'} {'confidence': 0.99, 'encoding': 'GB2312'} {'confidence': 0.99, 'encoding': 'GB2312'} {'confidence': 0.73, 'encoding': 'windows-1252'} {'confidence': 0.99, 'encoding': 'GB2312'}
可以看出编码GB2312的置信度最大,下面我们用GB2312编码来解码文件名,代码如下:
import os import chardet for file in os.listdir('./test'): r = file.decode('GB2312') print(r)
输出:
Python性能分析与优化.pdf
Python数据分析与挖掘实战.pdf
Python编程实战:运用设计模式、并发和程序库创建高质量程序.pdf
流畅的Python.pdf
编写高质量Python代码的59个有效方法.pdf
经过编码之后,文件名打印正确。
PS:chardet.detect检测的字符串越长越准确,越短越不准确
这里还有一个问题是上面的代码是在Windows下测试,Linux下文件名编码是utf-8,为了兼容Windows和Linux,代码需要修改一下,下面我们把代码封装到函数中:
# -*- coding: utf-8 -*- import os def get_filename_from_dir(dir_path): file_list = [] if not os.path.exists(dir_path): return file_list for item in os.listdir(dir_path): basename = os.path.basename(item) # print(chardet.detect(basename)) # 找出文件名编码,文件名包含有中文 # windows下文件编码为GB2312,linux下为utf-8 try: decode_str = basename.decode("GB2312") except UnicodeDecodeError: decode_str = basename.decode("utf-8") file_list.append(decode_str) return file_list # 测试代码 r = get_filename_from_dir('./test') for i in r: print(i)
先用GB2312解码,如果出错再用utf-8解码,这样就兼容了Windows和Linux(在Win7和Ubuntu16.04测试通过)。
以上这篇浅谈Python2获取中文文件名的编码问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持帮客之家。
相关内容
- django项目运行因中文而乱码报错的几种情况解决,dja
- Python2和Python3中print的用法示例总结,python2python3
- Python实现针对含中文字符串的截取功能示例,
- Python 爬虫之超链接 url中含有中文出错及解决办法,
- CentOS 6.5下安装Python 3.5.2(与Python2并存),centospython2
- Python实现针对中文排序的方法,
- Python结巴中文分词工具使用过程中遇到的问题及解决方
- Python3如何解决字符编码问题详解,python3详解
- WINDOWS 同时安装 python2 python3 后 pip 错误的解决方法,
- 解决uWSGI的编码问题详解,uwsgi编码详解
评论关闭