[Python] window10\Linux python unzip Chinese garbled

In the zip package, the encoding of the file name is not unicode. After viewing the source code, when the file flag is detected in the zipfile, only cp437 and utf-8 are supported. Specifically, look for the source code of zipfile.py to find the following code:

First place:

if flags & 0x800:
    # UTF-8 file names extension
    filename = filename.decode('utf-8')
else:
    # Historical ZIP filename encoding
    filename = filename.decode('cp437')

The second place:

if zinfo.flag_bits & 0x800:
    # UTF-8 filename
    fname_str = fname.decode("utf-8")
else:
    fname_str = fname.decode("cp437")

 

From the source code, it can be seen that except when the code is correctly recognized as utf8, it will be recognized and decoded as cp437 code, but if the actual decompressed file is gbk and other codes, it will become garbled. So the solution decode is gbk. The specific code is as follows:

First place:

if flags & 0x800:
    # UTF-8 file names extension
    filename = filename.decode('utf-8')
else:
    # Historical ZIP filename encoding
    # update ryanzheng
    # #filename = filename.decode('cp437')
    filename = filename.decode('gbk')
    # update ryanzheng

The second place:

if zinfo.flag_bits & 0x800:
    # UTF-8 filename
    fname_str = fname.decode("utf-8")
else:
    # update ryanzheng
    # fname_str = fname.decode("cp437")
    fname_str = fname.decode('gbk')
    # update ryanzheng

 

After the above modification. Overwrite the modified zipfile.py file C:\ProgramData\Anaconda3\Lib\[Everyone’s is different. It is to replace the file in the python environment you are running; execute the command in cmd: where python】zipfile.py in the directory

 

Processing on Linux: The same is to overwrite the modified zipfile.py file /usr/local/anaconda3/lib/python3.7/ [Everyone is different. It is to replace the file in the python environment you are running; type in the command line: whereis python】zipfile.py in the directory

tips: cd to the /usr/local/anaconda3/ directory. Then use the command: find ./ -name zipfile.py

 

to sum up:

1. The python operating environment needs to install the zip package

2. Modify the two codes of zipfile.py

3. Overwrite the original zipfile.py file

 

So far the garbled problem is solved! ! !

Guess you like

Origin blog.csdn.net/xiezhen_zheng/article/details/103009295