File I/O Python Built-in Data Type
NCCU Computer Science Dept.Python Programming for Non-Programmer
File I/OIntroduction
Recall & Warn Up
name = open(‘filename’, ‘w’)read()readline()readlines()write()writelines()
File I/OIntroduction
Get The Source
• goo.gl/18AIo
• Finish the code by yourself!
File I/OIntroduction
Declaration
def load_numbers(numbers, filename): pass
def save_numbers(numbers, filename): pass
File I/OIntroduction
Declaration
def load_numbers(numbers, filename): pass
def save_numbers(numbers, filename): pass
Fill them!
File I/OIntroduction
Two New Functions• Load Numbers
• Save Numbers
Variable File
Variable File
File I/OIntroduction
File FormatShould be just like below....
The President of Taiwan, 0912345678Google Incorporate, 02-12345678The President of NCCU, 02-29393091The Queen of NCCU dogs, xxxxxx.....
File I/OIntroduction
Load Numbers
def load_numbers(numbers, filename): in_file = open(filename, "rt")
# do something...
in_file.close()
First, declare the file object and the close method of the file
File I/OIntroduction
Load NumbersAnd 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/OIntroduction
Load Numbers
def load_numbers(numbers, filename): in_file = open(filename, "rt")
while True: in_line = in_file.readline() if not in_line: break in_line = in_line[:-1] in_file.close()
Remove the last character of newline(“\n”)
“The string\n”
“The string”
File I/OIntroduction
Load Numbersdef 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/OIntroduction
Save Numbersdef 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/OIntroduction
Finish
• Finish Code: goo.gl/DDK7d
• Practice by yourself