Dumb Q #1
Alex Martelli
aleax at aleax.it
Tue Jan 28 05:11:33 EST 2003
Norm wrote:
> 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[3] to 199
>
> Thoughts?
> 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[3] == "200":
> print fields[0], " has a GID of 200"
> print "now changing it to 199"
> fields[3] = 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[3] == "200":
print fields[0], " has a GID of 200"
print "now changing it to 199"
fields[3] = "199"
records[i] = ':'.join(fields)
and then of course you need to actually write the contents
of variable records back into the file...:
aFile.seek(0)
aFile.writelines(records)
aFile.close()
(using a variable name different from 'file', as I suggested).
Alex
More information about the Python-list
mailing list