OLD | NEW |
1 #! /usr/bin/env python | 1 #! /usr/bin/env python |
2 | 2 |
3 # See README.txt for information and build instructions. | 3 # See README.txt for information and build instructions. |
4 | 4 |
5 import addressbook_pb2 | 5 import addressbook_pb2 |
6 import sys | 6 import sys |
7 | 7 |
8 # This function fills in a Person message based on user input. | 8 # This function fills in a Person message based on user input. |
9 def PromptForAddress(person): | 9 def PromptForAddress(person): |
10 person.id = int(raw_input("Enter person ID number: ")) | 10 person.id = int(raw_input("Enter person ID number: ")) |
(...skipping 25 matching lines...) Expand all Loading... |
36 # adds one person based on user input, then writes it back out to the same | 36 # adds one person based on user input, then writes it back out to the same |
37 # file. | 37 # file. |
38 if len(sys.argv) != 2: | 38 if len(sys.argv) != 2: |
39 print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" | 39 print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" |
40 sys.exit(-1) | 40 sys.exit(-1) |
41 | 41 |
42 address_book = addressbook_pb2.AddressBook() | 42 address_book = addressbook_pb2.AddressBook() |
43 | 43 |
44 # Read the existing address book. | 44 # Read the existing address book. |
45 try: | 45 try: |
46 f = open(sys.argv[1], "rb") | 46 with open(sys.argv[1], "rb") as f: |
47 address_book.ParseFromString(f.read()) | 47 address_book.ParseFromString(f.read()) |
48 f.close() | |
49 except IOError: | 48 except IOError: |
50 print sys.argv[1] + ": File not found. Creating a new file." | 49 print sys.argv[1] + ": File not found. Creating a new file." |
51 | 50 |
52 # Add an address. | 51 # Add an address. |
53 PromptForAddress(address_book.people.add()) | 52 PromptForAddress(address_book.people.add()) |
54 | 53 |
55 # Write the new address book back to disk. | 54 # Write the new address book back to disk. |
56 f = open(sys.argv[1], "wb") | 55 with open(sys.argv[1], "wb") as f: |
57 f.write(address_book.SerializeToString()) | 56 f.write(address_book.SerializeToString()) |
58 f.close() | |
OLD | NEW |