权限被拒绝写入我的临时文件

Mac*_*ack 22 python temporary-files

我正在尝试使用Python在Windows操作系统上创建和写入临时文件.我使用Python模块tempfile创建了一个临时文件.

但是当我去写那个临时文件时,我收到了一个错误Permission Denied.我不允许写临时文件吗?!难道我做错了什么?如果我想创建和写入临时文件,我应该如何在Python中执行此操作?我想在临时目录中创建临时文件以用于安全目的而不是在本地(在.exe执行的目录中).

IOError: [Errno 13] Permission denied: 'c:\\users\\blah~1\\appdata\\local\\temp\\tmpiwz8qw'

temp = tempfile.NamedTemporaryFile().name
f = open(temp, 'w') # error occurs on this line
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 35

NamedTemporaryFile实际上为你创建了文件,你不需要打开它来写.

事实上,Python文档声明:

名称是否可以用于第二次打开文件,而命名的临时文件仍然是打开的,因此不同平台(它可以在Unix上使用; 它不能在Windows NT或更高版本上使用).

这就是你获得许可错误的原因.你可能会追求的是:

f = tempfile.NamedTemporaryFile(mode='w') # open file
temp = f.name                             # get name (if needed)
Run Code Online (Sandbox Code Playgroud)


小智 20

使用删除参数如下:

tmpf = NamedTemporaryFile(delete=False)
Run Code Online (Sandbox Code Playgroud)

但是,一旦完成,您需要手动删除临时文件。

tmpf.close()
os.unlink(tmpf.name)
Run Code Online (Sandbox Code Playgroud)

错误参考:https : //github.com/bravoserver/bravo/issues/111

问候, 维迪耶什

  • 即使我使用`with`语句,我是否需要手动删除? (3认同)

Eri*_*sty 7

考虑os.path.join(tempfile.gettempdir(), os.urandom(24).hex())改用。它是可靠的、跨平台的,唯一需要注意的是它不适用于 FAT 分区。

NamedTemporaryFile 有很多问题,其中最重要的是它可能会因为权限错误而无法创建文件,无法检测权限错误,然后循环数百万次,挂起您的程序和文件系统。


whe*_*eph 5

以下命名临时文件的自定义实现是在Erik Aronesty 的原始答案的基础上扩展的:

import os
import tempfile


class CustomNamedTemporaryFile:
    """
    This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:

    > Whether the name can be used to open the file a second time, while the named temporary file is still open,
    > varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
    """
    def __init__(self, mode='wb', delete=True):
        self._mode = mode
        self._delete = delete

    def __enter__(self):
        # Generate a random temporary file name
        file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
        # Ensure the file is created
        open(file_name, "x").close()
        # Open the file in the given mode
        self._tempFile = open(file_name, self._mode)
        return self._tempFile

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._tempFile.close()
        if self._delete:
            os.remove(self._tempFile.name)
Run Code Online (Sandbox Code Playgroud)