Heim  >  Artikel  >  Backend-Entwicklung  >  Python遍历zip文件输出名称时出现乱码问题的解决方法

Python遍历zip文件输出名称时出现乱码问题的解决方法

WBOY
WBOYOriginal
2016-06-06 11:23:591240Durchsuche

本文实例讲述了Python遍历zip文件输出名称时出现乱码问题的解决方法。分享给大家供大家参考。具体如下:

windows中使用python2.7遍历zip文件之后输出文件名等信息,console打印的中文及一些标点出现乱码。查了一下网上说的windows的编码为cp936,print()函数交给系统处理打印,所以要提前编码成windows能够识别的编码。

这种print的乱码也会出现在形如print(mylist)中(mylist是python的list类型变量,print(mylist[2])则不会乱码,奇怪)

代码如下:(.py文件中在文件头先加 # -*- coding: UTF-8 –*-)

import zipfile
def listzipfilesinfo(path):
  z=zipfile.ZipFile(path,'r')
  try:
    for filename in z.namelist():
      bytes=z.read(filename)
      print('File:%s Size:%s'%(unicode(filename, 'cp936').decode('utf-8'),len(bytes)))
  finally:
    z.close()

注:decode可以去掉

希望本文所述对大家的Python程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn