Skip to content Skip to sidebar Skip to footer

Python Fileinput Changes Permission

In my python code, I use the fileinput module for inplace replacing: import fileinput for line in fileinput.FileInput('permission.txt',inplace=1): line = line.strip() if n

Solution 1:

If you can help it, don't run your script as root.

EDIT Well, the answer has been accepted, but it's not really much of an answer. In case you must run the script as root (or indeed as any other user), you can use os.stat() to determine the user id and group id of the file's owner before processing the file, and then restore the file ownership after processing.

import fileinput
import os

# save original file ownership detailsstat = 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)

Post a Comment for "Python Fileinput Changes Permission"