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?
To change file permissions, you can use os. chmod(). You can bitwise OR the following options to set the permissions the way you want. These values come from the stat package: Python stat package documentation.
Python File writable() Method The writable() method returns True if the file is writable, False if not. A file is writable if it is opened using "a" for append or "w" for write.
chmod(path, 0444) is the Python command for changing file permissions in Python 2. x. For a combined Python 2 and Python 3 solution, change 0444 to 0o444 . You could always use Python to call the chmod command using subprocess .
You must be superuser or the owner of a file or directory to change its permissions. You can use the chmod command to set permissions in either of two modes: Absolute Mode – Use numbers to represent file permissions (the method most commonly used to set permissions).
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With