# -*- coding: utf8 -*-import re
import os
defsecure_filename(filename):from werkzeug._compat import text_type, PY2
ifisinstance(filename, text_type):from unicodedata import normalize
filename = normalize("NFKD", filename).encode("utf-8","ignore")# if not PY2:# filename = filename.decode("utf-8")
filename = filename.decode("utf-8")for sep in os.path.sep, os.path.altsep:if sep:
filename = filename.replace(sep," ")
_filename_ascii_strip_re = re.compile(u"[^A-Za-z0-9_\u4e00-\u9fa5.-]")
filename = _filename_ascii_strip_re.sub("","_".join(filename.split())).strip("._")# on nt a couple of special files are present in each folder. We# have to ensure that the target file is not such a filename. In# this case we prepend an underline
_windows_device_files =("CON","AUX","COM1","COM2","COM3","COM4","LPT1","LPT2","LPT3","PRN","NUL",)if(
os.name =="nt"and filename
and filename.split(".")[0].upper()in _windows_device_files
):
filename ="_"+ filename
return filename
filename=u"人民*/中国abc.xlsx"
filename = secure_filename(filename)print(filename)print(type(filename))"""
执行结果:
[root@lighthouse ~]# python secure_filename.py
人民_中国abc.xlsx
<type 'unicode'>
"""