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

标签 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

最佳答案

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/

相关文章:

python - 如何在Python中将字符串转换为int?

python - Osmnx 和 basemap

python - 长时间运行的子进程退出后清理临时文件夹

windows - 如何防止使用 GetTempFileName 创建的文件在重启时被自动删除

python - 无法删除由 `tempfile.mkstemp()` 在 Windows 上创建的文件

python - Django Session 在开发服务器中的生命周期

python - 关于学习曲线的具体形状

python - 如何通过python anaconda jupyter连接Azure sql数据库

java - 在不知道图像路径的情况下将图像添加到 JTooltip(由于图像是临时资源)

python - X-13-ARIMA 与 statsmodels.tsa.x13