下载的文件名总是乱码各平台的解决方法

https://sspai.com/post/44360

​ 说起「乱码」,没遇到过的电脑用户可能是极少的,尤其在国内中文环境下。暴露年龄的「烫烫烫」系列乱码已经绝迹,现如今遇到的往往是类似「%E9%AB%98%E9%A2%91」和「自在飞花轻似梦」的字符串。本文就这两种乱码情况分别给出解决方法。

首先应该说明的是,本文所说的方法是在出现文件名乱码情况下,如何恢复文件名的正确中文名称,并非一劳永逸地避免乱码的出现。这是由于下载文件名称乱码的出现,往往是系统、浏览器、网站三方面因素共同影响导致的,错综复杂。想要避免乱码的出现,只能根据具体的情况,对个人的系统或浏览器做出针对特定网站的调整配置。

# 调用 Python 内置模块进行解码
alias urldecode='python -c "import sys, urllib as ul; print ul.unquote_plus(sys.argv[1])"'

# 遍历选择的文件列表,进行重命名
for f in "$@"
do
    newName=$(urldecode "$f")
    mv "$f" "$newName"
done
for f in "$@"
do
    fileName=$(basename ${f})
    filePath=$(dirname ${f})

    # 两种乱码类型 GBK、UTF-8
    { fileNewName=$(echo $fileName | iconv -f UTF-8-Mac -t latin1 | iconv -f gbk)
    } || { fileNewName=$(echo $fileName | iconv -f UTF-8-Mac -t latin1)
    }

    # 文件名正常或乱码类型不属上述两种时,新文件名为空,则跳过
    if [ -n "$fileNewName" ]; then
        # 避免文件重复:如果已存在修复后的文件名,则在新文件名后加上随机字符串。
        if [ -e ${filePath}/$fileNewName ]; then
            mv "$f" "${filePath}/${fileNewName}-${RANDOM}"
        else
            mv "$f" "${filePath}/${fileNewName}"
        fi
    fi
done
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# uzip.py
#https://blog.csdn.net/babys/article/details/71405731?utm_source=blogxgwz9

import os
import sys
import zipfile

print "Processing File " + sys.argv[1]

file=zipfile.ZipFile(sys.argv[1],"r");
for name in file.namelist():
    utf8name=name.decode('gbk')
    print "Extracting " + utf8name
    pathname = os.path.dirname(utf8name)
    if not os.path.exists(pathname) and pathname!= "":
        os.makedirs(pathname)
    data = file.read(name)
    if not os.path.exists(utf8name):
        fo = open(utf8name, "w")
        fo.write(data)
        fo.close
file.close()

Search

    Table of Contents