Python:如何创建唯一的文件名?

发布于 2024-09-04 07:56:53 字数 377 浏览 3 评论 0原文

我有一个 python 网络表单,有两个选项 - 文件上传文本区域。我需要从每个中获取值并将它们传递给另一个命令行程序。我可以使用文件上传选项轻松传递文件名,但我不确定如何传递文本区域的值。

我认为我需要做的是:

  1. 生成一个唯一的文件名
  2. 在工作目录中创建一个具有该名称的临时文件
  3. 将从 textarea 传递的值保存到临时文件中
  4. 从我的 python 模块内部执行命令行程序并将其名称传递给它临时文件

我不知道如何生成唯一的文件名。有人可以给我一些关于如何生成唯一文件名的提示吗?任何算法、建议和代码行都值得赞赏。

感谢您的关心

I have a python web form with two options - File upload and textarea. I need to take the values from each and pass them to another command-line program. I can easily pass the file name with file upload options, but I am not sure how to pass the value of the textarea.

I think what I need to do is:

  1. Generate a unique file name
  2. Create a temporary file with that name in the working directory
  3. Save the values passed from textarea into the temporary file
  4. Execute the commandline program from inside my python module and pass it the name of the temporary file

I am not sure how to generate a unique file name. Can anybody give me some tips on how to generate a unique file name? Any algorithms, suggestions, and lines of code are appreciated.

Thanks for your concern

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

在风中等你 2024-09-11 07:56:53

我认为你的问题不是很清楚,但如果你需要的只是一个唯一的文件名......

import uuid

unique_filename = str(uuid.uuid4())

I didn't think your question was very clear, but if all you need is a unique file name...

import uuid

unique_filename = str(uuid.uuid4())
郁金香雨 2024-09-11 07:56:53

uuid 模块是一个不错的选择,我更喜欢使用 uuid.uuid4().hex 作为随机文件名,因为它将返回不带破折号的十六进制字符串< /强>。

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

The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

import uuid
filename = uuid.uuid4().hex

The outputs should like this:

>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one
半步萧音过轻尘 2024-09-11 07:56:53

如果你想在Python中创建临时文件,Python标准库中有一个名为 tempfile 的模块。如果您想启动其他程序来操作该文件,请使用 tempfile.mkstemp() 创建文件,并使用 os.fdopen() 访问 mkstemp() 为您提供的文件描述符。

顺便说一句,你说你正在从 Python 程序运行命令?您几乎肯定应该使用 subprocess 模块。

因此,您可以非常愉快地编写如下代码:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

运行该代码,您应该会发现 cat 命令运行得很好,但临时文件在 finally 块中被删除了。请注意,您必须删除 mkstemp() 自己返回的临时文件 - 库无法知道您何时完成它!

(编辑:我假设 NamedTemporaryFile 完全按照您的要求进行操作,但这可能不太方便 - 当临时文件对象关闭时,文件会立即被删除,并且在您关闭文件之前让其他进程打开该文件不适用于某些平台,尤其是 Windows。抱歉,我失败了。)

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

白首有我共你 2024-09-11 07:56:53

也许您需要独特的临时文件?

import tempfile

f = tempfile.NamedTemporaryFile(mode='w+b', delete=False)

print f.name
f.close()

f 是打开的文件。 delete=False 表示关闭后不删除文件。

如果您需要控制文件名,可以使用可选的 prefix=...suffix=... 参数来获取字符串。请参阅https://docs.python.org/3/library/tempfile.html

Maybe you need unique temporary file?

import tempfile

f = tempfile.NamedTemporaryFile(mode='w+b', delete=False)

print f.name
f.close()

f is opened file. delete=False means do not delete file after closing.

If you need control over the name of the file, there are optional prefix=... and suffix=... arguments that take strings. See https://docs.python.org/3/library/tempfile.html.

笑着哭最痛 2024-09-11 07:56:53

您可以使用 datetime 模块

import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')

请注意:
我正在使用 replace 因为许多操作系统中的文件名中不允许使用冒号。

就是这样,每次都会给你一个唯一的文件名。

You can use the datetime module

import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')

Note that:
I am using replace since the colons are not allowed in filenames in many operating systems.

That's it, this will give you a unique filename every single time.

四叶草在未来唯美盛开 2024-09-11 07:56:53

如果您需要简短的唯一 ID 作为文件名,请尝试 shortuuidshortuuid使用小写和大写字母和数字,并删除类似的字符,例如 l、1、I、O 和 0。

>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22

>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'

In case you need short unique IDs as your filename, try shortuuid, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.

>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22

compared to

>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'
一梦浮鱼 2024-09-11 07:56:53

我遇到了这个问题,我将为那些可能正在寻找类似问题的人添加我的解决方案。我的方法只是根据 ascii 字符创建一个随机文件名。它很可能是唯一的。

from random import sample
from string import digits, ascii_uppercase, ascii_lowercase
from tempfile import gettempdir
from os import path

def rand_fname(suffix, length=8):
    chars = ascii_lowercase + ascii_uppercase + digits

    fname = path.join(gettempdir(), 'tmp-'
                + ''.join(sample(chars, length)) + suffix)

    return fname if not path.exists(fname) \
                else rand_fname(suffix, length)

I came across this question, and I will add my solution for those who may be looking for something similar. My approach was just to make a random file name from ascii characters. It will be unique with a good probability.

from random import sample
from string import digits, ascii_uppercase, ascii_lowercase
from tempfile import gettempdir
from os import path

def rand_fname(suffix, length=8):
    chars = ascii_lowercase + ascii_uppercase + digits

    fname = path.join(gettempdir(), 'tmp-'
                + ''.join(sample(chars, length)) + suffix)

    return fname if not path.exists(fname) \
                else rand_fname(suffix, length)
梦在深巷 2024-09-11 07:56:53

这可以使用 ufp.path 模块中的 unique 函数来完成。

import ufp.path
ufp.path.unique('./test.ext')

如果当前路径存在“test.ext”文件。 ufp.path.unique 函数返回“./test (d1).ext”。

This can be done using the unique function in ufp.path module.

import ufp.path
ufp.path.unique('./test.ext')

if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.

月亮是我掰弯的 2024-09-11 07:56:53

要创建唯一的文件路径(如果存在),请使用随机包为文件生成新的字符串名称。您可以参考下面的代码。

import os
import random
import string

def getUniquePath(folder, filename):    
    path = os.path.join(folder, filename)
    while os.path.exists(path):
         path = path.split('.')[0] + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + '.' + path.split('.')[1]
    return path

现在您可以使用此路径来相应地创建文件。

To create a unique file path if its exist, use random package to generate a new string name for file. You may refer below code for same.

import os
import random
import string

def getUniquePath(folder, filename):    
    path = os.path.join(folder, filename)
    while os.path.exists(path):
         path = path.split('.')[0] + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + '.' + path.split('.')[1]
    return path

Now you can use this path to create file accordingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文