Dumb Q #1
aleax at aleax.it
Tue Jan 28 11:11:33 CET 2003
> I would like to open this unix passwd file and chang the GID of those who
> have a GID of 200 to 199
> This does everything except change fields to 199
> file = open ("passwd.txt" , "r+")
Don't use built-in names of types, such as "file", "list",
"tuple", etc, to name your own variables: get into the habit
of naming them in significant ways, or, worst case, at least
use "aFile", "someList", etc. One day you'll get strange
bugs if you abuse built-in type names in this tempting way.
> records = file.readlines()
> for record in records:
> fields = record.split(':')
> if fields == "200":
> print fields, " has a GID of 200"
> print "now changing it to 199"
> fields = 199
Better to use "199" of course -- a string, NOT a number. And
then of course you need to rebuild the record -- variable
"fields" is just holding copies of the record's data. It's
hard to do this when you iterate directly on the list: rebinding
variable 'record' would not affect list 'records', which is the
one you NEED to affect. So, you may want to loop on index,
instead, changing this loop into:
for i in range(len(records)):
fields = records[i].split(':')
if fields == "200":
print fields, " has a GID of 200"
print "now changing it to 199"
fields = "199"
records[i] = ':'.join(fields)
and then of course you need to actually write the contents
of variable records back into the file...:
(using a variable name different from 'file', as I suggested).
More information about the Python-list