Changing the permissions of a python file

In my Python code, I am using the fileinput module to replace inplace:

import fileinput

for line in fileinput.FileInput("permission.txt",inplace=1):
    line = line.strip()
    if not 'def' in line:
        print line
    else:
        line=line.replace(line,'zzz')
        print line


fileinput.close()

      

However, once that is done, the .txt permissions will now only be changed to root. I can no longer edit the file. I can only delete it.

I did some searches and he mentioned that it might be because fileinput is creating a temporary file for this read / write interaction.

However, I would have thought there would be a fix for this since the bug was reported in 1999. Do I have to do something in my code to keep the permissions the same? or is it an operating system level issue.

I am using Python 2.6.2 on Ubuntu 9.04

+2


source to share


1 answer


If you can do this, don't run the script as root.

EDIT Well, the answer was accepted, but it's not really a very big answer. If you must run the script as root (or just like any other user), you can use os.stat()

to determine the user id and group id of the file owner before processing the file, and then regain ownership of the file after processing.



import fileinput
import os

# save original file ownership details
stat = os.stat('permission.txt')
uid, gid = stat[4], stat[5]

for line in fileinput.FileInput("permission.txt",inplace=1):
    line = line.strip()
    if not 'def' in line:
        print line
    else:
        line=line.replace(line,'zzz')
        print line


fileinput.close()

# restore original file ownership
os.chown("permission.txt", uid, gid)

      

+2


source







All Articles