close

How do you create in python a file with permissions other users can write

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do you create in python a file with permissions other users can write in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do you create in python a file with permissions other users can write?

  1. How do you create in python a file with permissions other users can write?

    The problem is your call to open() recreates the call. Either you need to move the chmod() to after you close the file, OR change the file mode to w+.

  2. create in python a file with permissions other users can write

    The problem is your call to open() recreates the call. Either you need to move the chmod() to after you close the file, OR change the file mode to w+.

Method 1

If you don’t want to use os.chmod and prefer to have the file created with appropriate permissions, then you may use os.open to create the appropriate file descriptor and then open the descriptor:

import os
# The default umask is 0o22 which turns off write permission of group and others
os.umask(0)
with open(os.open('filepath', os.O_CREAT | os.O_WRONLY, 0o777), 'w') as fh:
  fh.write(...)

Python 2 Note:

The built-in open() in Python 2.x doesn’t support opening by file descriptor. Use os.fdopen instead; otherwise you’ll get:

TypeError: coercing to Unicode: need string or buffer, int found.

Method 2

The problem is your call to open() recreates the call. Either you need to move the chmod() to after you close the file, OR change the file mode to w+.

Option1:

with open("/home/pi/test/relaxbank1.txt", "w+") as fh:
    fh.write(p1)
os.chmod("/home/pi/test/relaxbank1.txt", 0o777)

Option2:

os.chmod("/home/pi/test/relaxbank1.txt", 0o777)
with open("/home/pi/test/relaxbank1.txt", "w+") as fh:
    fh.write(p1)

Comment: Option1 is slightly better as it handles the condition where the file may not already exist (in which case the os.chmod() will throw an exception).

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read