gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:45:13 27 4
gpt4 key购买 nike

我正在尝试使用 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

最佳答案

NamedTemporaryFile实际上是为你创建并打开文件,你不需要再次打开它来写。

事实上,Python docs状态:

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).

这就是您收到权限错误的原因。您可能想要的是:

f = tempfile.NamedTemporaryFile(mode='w') # open file
temp = f.name # get name (if needed)

关于python - 写入我的临时文件的权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23212435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com