Dumb Q #1
Alex Martelli
aleax at aleax.it
Wed Jan 29 10:08:14 EST 2003
Grant Edwards wrote:
> In article <mailman.1043758549.8656.python-list at python.org>, Andy Jewell
> wrote:
>
>> for record in records[:]:
>>
>> 2) Rewrite the records list back to the file. Modifying the records
>> /list/ merely changes the copy in memory.
>
> Writing to a file like /etc/passwd is generally considered "A
> Bad Thing". When you want to change a critical (and "live")
> file whose corruption will render your system inoperable,
> always use a temporary file and then rename it.
Incidentally, module fileinput can do that for you -- when you
specify the parameter requesting "inline rewrite" of the files
being processed, what fileinput does under the cover is exactly
this -- write to temporary files and replace the input files
with the temporary ones when each is done.
So...:
import fileinput
for line in fileinput.input('/etc/passwd', inplace=1):
fields = line.split(':')
if fields[3] == "200":
fields[3] = 199
line = ':'.join(fields)
print line,
Alex
More information about the Python-list
mailing list