Permission Denied To Write To My Temporary File

痴心易碎 提交于 2019-11-26 16:58:33

问题


I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.

But when I go to write that temporary file I get an error Permission Denied. Am I not allowed to write to temporary files?! Am I doing something wrong? If I want to create and write to a temporary file how should should I do it in Python? I want to create a temporary file in the temp directory for security purposes and not locally (in the dir the .exe is executing).

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

回答1:


NamedTemporaryFile actually creates the file for you, there's no need for you to open it for write.

In fact, the Python docs state:

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

That's why you're getting your permission error. What you're probably after is:

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



回答2:


Use the delete parameter as below:

tmpf = NamedTemporaryFile(delete=False)

But then you need to manually delete the temporary file once you are done with it.

tmpf.close()
os.unlink(tmpf.name)

Reference for bug: https://github.com/bravoserver/bravo/issues/111

regards, Vidyesh




回答3:


Consider using os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) instead. It's reliable, cross-platform, and the only caveat is that it doesn't work on FAT partitions.

NamedTemporaryFile has a number of issues, not the least of which is that it can fail to create files because of a permission error, fail to detect the permission error, and then loop millions of times, hanging your program and your filesystem.




回答4:


Permission was denied because the file is Open during line 2 of your code.

close it with f.close() first then you can start writing on your tempfile



来源:https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!