10

使用Python创建随机文件名

 3 years ago
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

本条目发布于2018年7月25日。属于技术笔记分类,被贴了 Python 标签。 ← Flask问题集散地:Flask-China Flask Web开发实战番外 →

撰写评论 取消回复

电子邮件地址不会被公开,必填项已用*标出。

评论

姓名 *

电子邮件 *

站点

在此浏览器中保存我的名字、电邮和网站。

当有人回复我时,发送电子邮件提醒我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK