Updated python examples to use with.

This commit is contained in:
Parth Kolekar 2016-01-26 04:13:31 +05:30
parent 60f7fc51fb
commit 21e1f1d2e9
2 changed files with 6 additions and 9 deletions

View file

@ -43,9 +43,8 @@ address_book = addressbook_pb2.AddressBook()
# Read the existing address book. # Read the existing address book.
try: try:
f = open(sys.argv[1], "rb") with open(sys.argv[1], "rb") as f:
address_book.ParseFromString(f.read()) address_book.ParseFromString(f.read())
f.close()
except IOError: except IOError:
print sys.argv[1] + ": File not found. Creating a new file." print sys.argv[1] + ": File not found. Creating a new file."
@ -53,6 +52,5 @@ except IOError:
PromptForAddress(address_book.people.add()) PromptForAddress(address_book.people.add())
# Write the new address book back to disk. # Write the new address book back to disk.
f = open(sys.argv[1], "wb") with open(sys.argv[1], "wb") as f:
f.write(address_book.SerializeToString()) f.write(address_book.SerializeToString())
f.close()

View file

@ -31,8 +31,7 @@ if len(sys.argv) != 2:
address_book = addressbook_pb2.AddressBook() address_book = addressbook_pb2.AddressBook()
# Read the existing address book. # Read the existing address book.
f = open(sys.argv[1], "rb") with open(sys.argv[1], "rb") as f:
address_book.ParseFromString(f.read()) address_book.ParseFromString(f.read())
f.close()
ListPeople(address_book) ListPeople(address_book)