Write file with specific permissions in Python

lfaraone picture lfaraone · Apr 11, 2011 · Viewed 64.4k times · Source

I'm trying to create a file that is only user-readable and -writable (0600).

Is the only way to do so by using os.open() as follows?

import os
fd = os.open('/path/to/file', os.O_WRONLY, 0o600)
myFileObject = os.fdopen(fd)
myFileObject.write(...)
myFileObject.close()

Ideally, I'd like to be able to use the with keyword so I can close the object automatically. Is there a better way to do what I'm doing above?

Answer

vartec picture vartec · Apr 11, 2011

What's the problem? file.close() will close the file even though it was open with os.open().

with os.fdopen(os.open('/path/to/file', os.O_WRONLY | os.O_CREAT, 0o600), 'w') as handle:
  handle.write(...)