6. Two New Functions
• Load Numbers
Variable File
• Save Numbers
Variable File
File I/O
Introduction
7. File Format
Should be just like below....
The President of Taiwan, 0912345678
Google Incorporate, 02-12345678
The President of NCCU, 02-29393091
The Queen of NCCU dogs, xxxxxx
.....
File I/O
Introduction
8. Load Numbers
First, declare the file object and
the close method of the file
def load_numbers(numbers, filename):
in_file = open(filename, "rt")
# do something...
in_file.close()
File I/O
Introduction
9. Load Numbers
And make a while loop for reading lines of file
def load_numbers(numbers, filename):
in_file = open(filename, "rt")
while True:
in_line = in_file.readline()
if not in_line:
break
in_file.close()
File I/O
Introduction
10. Load Numbers
Remove the last character of newline(“n”)
def load_numbers(numbers, filename):
in_file = open(filename, "rt") “The stringn”
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1] “The string”
in_file.close()
File I/O
Introduction
11. Load Numbers
def load_numbers(numbers, filename):
in_file = open(filename, "r")
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, number = in_line.split(‘,’) # split to two parts
numbers[name] = number # save them to numbers
in_file.close()
File I/O
Introduction
12. Save Numbers
def save_numbers(numbers, filename):
out_file = open(filename, "w")
for k, v in numbers.items():
out_file.write(k + "," + v + "n")
out_file.close()
Multiple assignment:
(k, v) = [“name”, “phone”]
>>> k
“name”
>>> v
“phone” File I/O
Introduction