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'
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.