Dumb Q #1
aleax at aleax.it
Wed Jan 29 16:08:14 CET 2003
Grant Edwards wrote:
> In article <mailman.1043758549.8656.python-list at python.org>, Andy Jewell
>> 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.
for line in fileinput.input('/etc/passwd', inplace=1):
fields = line.split(':')
if fields == "200":
fields = 199
line = ':'.join(fields)
More information about the Python-list