Python mkstemp后缀

时间:2013-03-18 11:46:09

标签: python mkstemp

我在我工作的Django项目中有以下代码处理图像上传:

def upload_handler(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=MEDIA_ROOT)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
        return MEDIA_URL + basename(dest.name)

上传部分一切正常,但mkstemp在扩展后添加了6个随机后缀(Ex.test.png - > test.pngbFVeyh)。即使我在第二个代码行中传递后缀,它也会附加它,但也会附加6个随机字符。发生的其他奇怪的事情是,在上传文件夹(在我的情况下是MEDIA_ROOT)中,它与另一个与图片同名的空纯文本文档类型文件一起创建(例如,test.pngbFVeyh)。我已经阅读了有关mkstemp的文档,但我没有找到任何替代解决方案。

2 个答案:

答案 0 :(得分:1)

def upload_handler(source):
    # this is creating a temp file and returning an os handle and name
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=MEDIA_ROOT)
    # this next line just clears the file you just made (which is already empty)
    with open(filepath, 'wb') as dest: 
        # this is a strange way to get a fobj to copy :)
        shutil.copyfileobj(source, dest)
        return MEDIA_URL + basename(dest.name)

前缀和后缀就是这样做的,因此如果您不希望文件名以临时字符开头或结尾,则需要使用前缀后缀。例如,

name = os.path.basename(source.name)
prefix, suffix = os.path.splitext(name)
_, filepath = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=MEDIA_ROOT)

但是如果你使用tempfile.NamedTemporaryFile会更好,因为那样会返回类似文件的对象(所以你不必从文件名创建fobj,默认情况下会删除临时文件)完成)。

fobj, _ = tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, dir=MEDIA_ROOT)
shutil.copyfileobj(source, fobj)

答案 1 :(得分:-1)

该名称是随机生成的,因为它是tempfile.mkstemp的目的。创建具有该名称的文件,因为它是tempfile.mkstemp的工作方式。它也会打开,文件描述符将在您忽略的fd中返回给您。您似乎不明白应该如何使用tempfile.mkstemp,而您可能需要使用其他内容。

相关问题