在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.
完整参数set:
Full parameter set:
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'
其他使用临时文件的例子可以在这里找到
Additional examples for working with temporary files can be found here
这篇关于在Python中生成随机文件名的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!