Advertisement
Guest User

4 ways to parse a passwd file in Python

a guest
Sep 4th, 2010
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. ### 1 (6 lines)
  2.  
  3. def passwd_data(filename):
  4.     fields='username:password:uid:gid:fullname:homedir:shell'.split(':')
  5.     FILE = open(filename, "r")
  6.     passwdfile=[y.strip() for y in FILE.readlines()]
  7.     FILE.close()
  8.     return [dict(zip(fields, line.split(':'))) for line in passwdfile]
  9.  
  10. ### 2 (9 lines, but stripallf is a generic, reusable function)
  11. def stripallf(filename):
  12.     FILE = open(filename, "r")
  13.     lines=[y.strip() for y in FILE.readlines()]
  14.     FILE.close()
  15.     return lines
  16.  
  17. def passwd_data2(filename):
  18.     return [dict(zip('username:password:uid:gid:fullname:homedir:shell'.split(':'),
  19.                      line.split(':'))) for line in stripallf(filename)]
  20.  
  21. ### 3 (10 lines, 1 import)
  22. from copy import deepcopy
  23.  
  24. def passwd_data3(filename):
  25.     dic={}; lst=[]
  26.     FILE = open(filename, "r")
  27.     for line in FILE:
  28.         (dic['username'], dic['password'], dic['uid'], dic['gid'], dic['fullname'], dic['homedir'], dic['shell']) = line.strip().split(':')
  29.         lst.append(deepcopy(dic))
  30.     FILE.close()
  31.     return lst
  32.  
  33. ### 4 (11 lines)
  34. class passwd_line():
  35.     def __init__(self, pwdline):
  36.         (self.username, self.password, self.uid, self.gid, self.fullname, self.homedir, self.shell) = pwdline.strip().split(':')
  37.     def __getitem__(self, key):
  38.         return self.__dict__[key]
  39.  
  40. def passwd_data4(filename):
  41.     FILE = open(filename, "r")
  42.     passwdfile=[y.strip() for y in FILE.readlines()]
  43.     FILE.close()
  44.     return [passwd_line(line) for line in passwdfile]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement