Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write file with specific permissions in Python

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?

like image 472
lfaraone Avatar asked Apr 11 '11 16:04

lfaraone


People also ask

How do you give permission to a file in Python?

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.

How do I make a file writable in Python?

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.

How do you change permissions on a Python script?

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 .

How do I give permission to write a file?

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).


1 Answers

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(...) 
like image 99
vartec Avatar answered Sep 24 '22 06:09

vartec