0

Recently, I have discovered the "tempfile" module, which enables you to easily create temporary files used by your Python program.
However, while trying to use the module, I have discovered an issue - Most Python modules that manipulate or create files, use the path to the file (as a string) as inputs from the user (or a programmer).

That means, that code like this one will raise an error:

import tempfile

with tempfile.NamedTemporaryFile(suffix=".jpg") as tempfileimg:

    image = generate_random_image()
    save_image(image, tempfileimg)      # Type Error (expected path to file)
    upload_image_to_cloud(tempfileimg)  # Type Error (expected path to file)

    # In this example, both `save_image` and `upload_image_to_cloud` functions
    # expect to receive the path to the file and not the "opened file object".

I have tried using tempfileimg.name to get the path to the temporary file as a string, but because temporary files are located in a special folder on the machine, writing files in the regular methods will raise an expectation:

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\MyUserName\\AppData\\Local\\Temp\\tmpvq81yj2v.jpg'

How can I solve this issue?

ppwater
  • 2,315
  • 4
  • 15
  • 29
RealA10N
  • 120
  • 1
  • 5
  • 19
  • 1
    Could you edit your question to include the full text of the error you get when you try to use `tempfileimg.name`? The permission denied error is odd. – Josh Karpel Nov 28 '20 at 01:18
  • are u on windows? – Lior Cohen Nov 28 '20 at 02:07
  • @LiorCohen Yes, I'm using Windows. – RealA10N Nov 28 '20 at 09:55
  • @JoshKarpel Added the full error to the question. Be aware that using the `name` property does not raise the exception, but trying to open the file does. – RealA10N Nov 28 '20 at 10:03
  • Can you clarify what exactly you are asking? It appears that the issue is a mismatch of file permissions, not getting the file path. No matter *how* you get the tempfile's path, if it is not writeable then it is not writeable. – MisterMiyagi Nov 28 '20 at 10:13
  • @MisterMiyagi I can write to the temporary file using the `write` method. However, I cannot open the file from "outside", and I can only access it using the tempfile instance. – RealA10N Nov 28 '20 at 10:38
  • Does this answer your question? [Python tempfile with a context manager on Windows 10 leads to PermissionError: \[Errno 13\]](https://stackoverflow.com/questions/55081022/python-tempfile-with-a-context-manager-on-windows-10-leads-to-permissionerror) – MisterMiyagi Nov 28 '20 at 10:45
  • 1
    Note that as per the docs for NamedTempFile: ["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**)."](https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile) You might be using the wrong tool for your task. – MisterMiyagi Nov 28 '20 at 10:49

0 Answers0