0

I would like to open and write to files in python's tempfile.TemporaryDirectory()

This is my code so far:

import tempfile

temp_dir = tempfile.TemporaryDirectory()

destination = temp_dir.name
file = 'concept_aliases.json'
spath = os.path.join(destination,"/",file)
with open(spath, "w+") as f::
   # do smthg

However, I am getting this error:

PermissionError: [Errno 13] Permission denied: '/concept_aliases.json'
Farrandi
  • 41
  • 2
  • This is possibly the same question as https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file – PreciXon Dec 03 '21 at 22:54
  • Get rid of the `"/"` parameter to `os.path.join()` - the whole point of that function is that it supplies the appropriate pathname separator for you. What's happening here is that the slash is being interpreted as an absolute pathname (to the root directory); everything previous gets discarded, and you end up with a reference to a file *in* the root directory (which you don't have permission to write to). – jasonharper Dec 03 '21 at 23:06

1 Answers1

1

The problem here is the slash / that is passed as the second argument to the os.path.join() method. As per documentation, join() does the following:

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

The crucial part however, is the following sentence:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

By passing a slash / as the second argument to join(), you actually start a new absolute path which, in return, discards all previous components.

With that being said, the correct approach in this context would be the following:

spath = os.path.join(destination, file)
bajro
  • 1,199
  • 3
  • 20
  • 33