Create (sane/safe) filename from any (unsafe) string

前端 未结 11 1378
醉酒成梦
醉酒成梦 2020-12-28 12:45

I want to create a sane/safe filename (i.e. somewhat readable, no \"strange\" characters, etc.) from some random Unicode string (mich might contain just anything).

(

11条回答
  •  半阙折子戏
    2020-12-28 13:41

    If you don't mind to import other packages, then werkzeug has a method for sanitizing strings:

    from werkzeug.utils import secure_filename
    
    secure_filename("hello.exe")
    'hello.exe'
    secure_filename("/../../.ssh")
    'ssh'
    secure_filename("DROP TABLE")
    'DROP_TABLE'
    
    #fork bomb on Linux
    secure_filename(": () {: |: &} ;:")
    ''
    
    #delete all system files on Windows
    secure_filename("del*.*")
    'del'
    

    https://pypi.org/project/Werkzeug/

提交回复
热议问题