chmod 777 to python script

Question:

Trying to translate linux cmd to python script

Linux cmds:

chmod 777 file1 file1/tmp file2 file2/tmp file3 file3/tmp

I know of os.chmod(file, 0777) but I’m not sure how to use it for the above line.

Asked By: Xandy

||

Answers:

os.chmod takes a single filename as argument, so you need to loop over the filenames and apply chmod:

files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
    os.chmod(file, 0o0777)

BTW i’m not sure why are you setting the permission bits to 777 — this is asking for trouble. You should pick the permission bits as restrictive as possible.

Answered By: heemayl

chmod 777 will get the job done, but it’s more permissions than you likely want to give that script.

It’s better to limit the privileges to execution.

I suggest: chmod +x myPthonFile.py

Answered By: benhorgen

If you want to use pathlib, you can use .chmod() from that library

from pathlib import Path

files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
    Path(file).chmod(0o0777)
Answered By: edesz

os.chmod() is one approach in python through which we can change the mode of path to the numeric mode similar to chmod 777 in linux.

Syntax: os.chmod(filepath, mode)

import os
import stat
# In Windows 
os.chmod(file_name, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
# In Linux
os.chmod(file_name, 0o555)
Answered By: Sravya Yellapragada
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.