使用tempfile.NamedTemporaryFile()报错PermissionError: [Errno 13] Permission denied
程序员文章站
2022-03-16 10:14:08
如果帮助您解决了问题,请点个赞吧????...
有问题就先查一下官方文档,内容如下:
"""
tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file
system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the returned file-like
object. 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). If delete is true (the default), the file is deleted as
soon as it is closed.The returned object is always a file-like object whose file attribute is the underlying true file object.
This file-like object can be used in a with statement, just like a normal file.
"""
# 翻译如下
"""
该功能的运行方式完全相同TemporaryFile(),只是保证文件在文件系统中具有可见的名称(在Unix上,目录条目未取消链接)。
可以从name返回的类似文件的对象的属性中检索该名称。在命名的临时文件仍处于打开状态时,是否可以使用该名称第二次打开文件,
会因平台而异(可以在Unix上使用;在Windows NT或更高版本上不能使用)。如果delete为true(默认设置),则在关闭文件后立即将其删除。
返回的对象始终是类似文件的对象,其file 属性是基础真实文件对象。with就像普通文件一样,可以在语句中使用该文件状对象。
"""
在使用tempfile.NamedTemporaryFile()创建临时文档后,不能对文件进行读写操作,因为创建的是临时文档,文件被关闭后会自动删除。
import tempfile
import json
data = [{'name': 'rocky', 'like': ('python', 'c++'), 'age': 23}]
# NamedTemporaryFile会在退出时,删除该文件,加上delete=False后会保留该文件,这样可以对文件再次操作
f = tempfile.NamedTemporaryFile(mode='w+')
# f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
json.dump(data, f)
f.flush()
# f.close()
print(open(f.name, 'r').read())
# f.remove()
# 运行结果如下:
"""
aceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\Programs\PyCharm 2018.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "D:\Programs\PyCharm 2018.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "G:/A_Code/Python_Code/Python_exe/lib_json.py", line 11, in <module>
print(open(f.name, 'r').read())
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Duke\\AppData\\Local\\Temp\\tmpjwaq13hs'
"""
**
如果想对其进行操作,需要在创建文档时加上delete=False
**
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
本文地址:https://blog.csdn.net/K_Duke/article/details/107643714