10
使用Python创建随机文件名
source link: https://greyli.com/python-random-filename/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
使用Python创建随机文件名
当用户上传文件时,为了进行统一处理,我们可以为所有文件创建随机文件名。Python标准库中的uuid
模块很适合用来生成文件名。我一般会使用uuid.uuid4().hex
作为随机文件名,因为它会返回16进制字符串形式的uuid,并且不包含连字符,更易读:
import uuid
filename = uuid.uuid4().hex
和其他常见方式的输出对比:
>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304' # <-- this one
这篇文章原发于我在Stack Overflow上的这个回答:https://stackoverflow.com/a/44992275/5511849
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK