Solution to the problem of garbled code when Python traverses the output name of zip file

  • 2020-05-07 19:55:05
  • OfStack

In this paper, an example is given to solve the problem of garbled code when Python traverses the output name of zip file. Share with you for your reference. The details are as follows:

windows USES python2.7 to iterate over the zip file and output the file name and other information. The Chinese text and some punctuation of console print are garbled. The code of windows mentioned on the Internet is cp936, and the print() function is handed to the system for printing, so it should be coded into the code that windows can recognize in advance.

This print garble will also appear in the form print(mylist) (mylist is list type variable of python, print(mylist[2]) will not garble, strange)

The code is as follows: (in the.py file, add # -* -coding: UTF-8 at the beginning of the file. *-)


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()

Note: decode can be removed

I hope this article has been helpful to your Python programming.


Related articles: