Advertisement
gruntfutuk

homework week3

Mar 26th, 2017
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.85 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Homework week 3
  3.  
  4. # store command line arguments in a dictionary, in a list, in a file
  5. # append to list on file on subsequent runs
  6. # (only ever one stored list, but will contain dictionary for every run)
  7.  
  8. import sys   # for command line arguments
  9. import json  # so can read/write data/files in JSON format
  10. import os    # to check for file existing using op system
  11.  
  12. dictFile = 'hw3alt.json'  # name of file to store dictionary of args
  13. argKeys = ['scriptname', 'firstname', 'lastname',
  14.            'genderid', 'location', 'status', 'misc']  # key names for args
  15.  
  16.  
  17. # function to do the bulk of the work of the programme
  18. def addArgs(f):
  19.     # first, add command line arguments to a new dictionary
  20.     args = dict(zip(argKeys, sys.argv))  # add with matching keys by position
  21.     # add any excess arguments as a list
  22.     if len(sys.argv) > len(argKeys):
  23.         args['unusedargs'] = sys.argv[len(argKeys):]
  24.  
  25.     # retrieve any stored dictionary list of command line arguments
  26.     if os.stat(dictFile).st_size > 0:
  27.         arglist = json.load(f)
  28.     else:
  29.         arglist = []
  30.  
  31.     # append new dictionary of command line args to list (empty or reloaded)
  32.     arglist.append(args)        # add new arguments dictionary to list
  33.  
  34.     # write latest version of list of dictionaries to file
  35.     f.seek(0)
  36.     json.dump(arglist, f)       # write (or overwrite previous) dictionary list
  37.     f.truncate()
  38.  
  39.  
  40. # if dictionary file exists (empty or not) add args, otherwise complain
  41. def main():
  42.     try:
  43.         with open(dictFile, 'r+') as f:  # open file for read/write
  44.             addArgs(f)                   # add the cl args to dict list file
  45.     except IOError as e:                 # throw error if no file or can't write
  46.         print('Trouble opening file {}.'.format(dictFile))
  47.         return e
  48.  
  49.  
  50. if __name__ == '__main__':
  51.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement