1

I am using the tempfile Python module to create a temporary file. I need to write to the file, and then I need to change the mode of the file so it is read-only (chmod 400). Is there a way I can do this using the tempfile module itself? Or should I look into using subprocess to achieve this? E.g subprocess.run(["chmod", "400", tmp_file.name])

Here's an example:

import tempfile

tmp_file = tempfile.NamedTemporaryFile() # by default this tempfile will have write permissions
tmp_file.write(b'Hello world!')

tmp_file.chmod(400) # I need to be able to change the permissions of the tempfile after I've written to it
  • You can `chmod` the file like you would `chmod` any file, using `os.chmod` method. But question is, why would you want to do this – Rahul Bharadwaj Feb 05 '21 at 16:40
  • Does this answer your question? [Changing file permission in Python](https://stackoverflow.com/questions/16249440/changing-file-permission-in-python) – Kev Feb 05 '21 at 16:43
  • Does this answer your question? [Change open file access mode](https://stackoverflow.com/questions/29595239/change-open-file-access-mode) – StefanMZ Feb 05 '21 at 16:53
  • Doh! os.chmod would definitely be best, but was just wondering if there was a way to achieve this that's built into the tempfile module. Looks like there isn't so gonna work with os.chmod(). Thanks all – Caleb Whittington Feb 08 '21 at 16:42

0 Answers0