在 Python 中生成随机文件名的最佳方法 [英] Best way to generate random file names in Python
问题描述
在 Python 中,生成一些随机文本以添加到我保存到服务器的文件(名称)的好方法或最佳方法是什么,只是为了确保它不会覆盖.谢谢!
In Python, what is a good, or the best way to generate some random text to prepend to a file(name) that I'm saving to a server, just to make sure it does not overwrite. Thank you!
推荐答案
Python 具有生成临时文件名的功能,请参阅 http://docs.python.org/library/tempfile.html.例如:
Python has facilities to generate temporary file names, see http://docs.python.org/library/tempfile.html. For instance:
In [4]: import tempfile
每次调用 tempfile.NamedTemporaryFile()
都会产生一个不同的临时文件,其名称可以通过 .name
属性访问,例如:
Each call to tempfile.NamedTemporaryFile()
results in a different temp file, and its name can be accessed with the .name
attribute, e.g.:
In [5]: tf = tempfile.NamedTemporaryFile()
In [6]: tf.name
Out[6]: 'c:\blabla\locals~1\temp\tmptecp3i'
In [7]: tf = tempfile.NamedTemporaryFile()
In [8]: tf.name
Out[8]: 'c:\blabla\locals~1\temp\tmpr8vvme'
一旦您拥有唯一的文件名,就可以像使用任何常规文件一样使用它.注意:默认情况下,文件将被删除关闭.但是,如果 delete
参数为 False,则文件不是自动删除.
Once you have the unique filename it can be used like any regular file. Note: By default the file will be deleted when it is
closed. However, if the delete
parameter is False, the file is not
automatically deleted.
完整参数集:
tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
还可以为临时文件指定前缀(作为可以在文件创建期间提供的各种参数之一):
it is also possible to specify the prefix for the temporary file (as one of the various parameters that can be supplied during the file creation):
In [9]: tf = tempfile.NamedTemporaryFile(prefix="zz")
In [10]: tf.name
Out[10]: 'c:\blabla\locals~1\temp\zzrc3pzk'
可以在此处
这篇关于在 Python 中生成随机文件名的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!