問題:
Python2獲取包含中文的文件名是如果不轉(zhuǎn)碼會出現(xiàn)亂碼。
這里假設要測試的文件夾名為test,文件夾下有5個文件名包含中文的文件分別為:
Python性能分析與優(yōu)化.pdf
Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn).pdf
Python編程實戰(zhàn):運用設計模式、并發(fā)和程序庫創(chuàng)建高質(zhì)量程序.pdf
流暢的Python.pdf
編寫高質(zhì)量Python代碼的59個有效方法.pdf
我們先不轉(zhuǎn)碼直接打印獲取到的文件名,代碼如下:
import osfor file in os.listdir('./test'): print(file)輸出亂碼:
Python���ܷ������Ż�.pdfPython���ݷ������ھ�ʵս.pdfPython���ʵս���������ģʽ�������ͳ���ⴴ������������.pdf������Python.pdf��д������Python�����59����Ч����.pdf
解決:
先測試一下文件名的編碼,這里我們用到chardet模塊,安裝命令:
pip install chardet
用chardet.detect函數(shù)檢測一下文件名的編碼方式:
{'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 osimport chardetfor file in os.listdir('./test'): r = file.decode('GB2312') print(r)輸出:
Python性能分析與優(yōu)化.pdf
Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn).pdf
Python編程實戰(zhàn):運用設計模式、并發(fā)和程序庫創(chuàng)建高質(zhì)量程序.pdf
流暢的Python.pdf
編寫高質(zhì)量Python代碼的59個有效方法.pdf
經(jīng)過編碼之后,文件名打印正確。
PS:chardet.detect檢測的字符串越長越準確,越短越不準確
這里還有一個問題是上面的代碼是在Windows下測試,Linux下文件名編碼是utf-8,為了兼容Windows和Linux,代碼需要修改一下,下面我們把代碼封裝到函數(shù)中:
# -*- coding: utf-8 -*-import osdef 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)            
新聞熱點
疑難解答