Edit python file

0

I need to do a small program in python to edit a file with superuser permissions. I think it's pretty simple but I've never worked with file management in python.

I have a file that according to an entry or value of a variable, I would have to remove a comment one line (delete //), and comment another (add //). This file allows you to configure another small program.

Thank you very much for your help and comments.

Greetings,

daniel

    
asked by dani68k 20.03.2018 в 07:22
source

1 answer

1

Finally, by researching and testing some solutions, I'm left with this:

def replace_line (file_name, line_num, text):

lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines)
out.close()

replace_line ('/ home / pi / test.txt', 5, 'Line 5 \ n') ## overwrite on line 5 **

Better to overwrite the line than to try to delete and insert // of the comments.

Thank you!

Greetings,

daniel

    
answered by 23.03.2018 в 08:14