0

I am creating a file with the open(file.py,"w") command. The file.py that is created has read and write permissions but I cannot exceute it.

What is the best way to create a file that I can run afterwards?

Should I, after creating the file and closing it, use os.chmod(file.py,0777)?

tshepang
  • 12,111
  • 21
  • 91
  • 136
NimrodB
  • 153
  • 3
  • 13

1 Answers1

0

Looking at the documentation for open, there is no attribute that specifies execution privileges. Instead, use chmod, as you mentioned in your question, but avoid using magic numbers and don't give all privileges to all users unless you know what they might do.

import os
from stat import S_IEXEC

file_name = "something_good.py"

with open(file_name, "w") as fp:
    write_something_to_file(fp)

os.chmod(file_name, S_IEXEC | os.stat(file_name).st_mode)
ilent2
  • 5,171
  • 3
  • 21
  • 30