Python-FileIO

13
File I/O Python Built-in Data Type NCCU Compur Science Dept. Pyon Programming for Non-Programmer

description

Python File I/O IntroductionNCCU Computer Science Dept.Python Programming for Non-programmer

Transcript of Python-FileIO

Page 1: Python-FileIO

File I/O Python Built-in Data Type

NCCU Computer Science Dept.Python Programming for Non-Programmer

Page 2: Python-FileIO

File I/OIntroduction

Recall & Warn Up

name = open(‘filename’, ‘w’)read()readline()readlines()write()writelines()

Page 3: Python-FileIO

File I/OIntroduction

Get The Source

• goo.gl/18AIo

• Finish the code by yourself!

Page 4: Python-FileIO

File I/OIntroduction

Declaration

def load_numbers(numbers, filename): pass

def save_numbers(numbers, filename): pass

Page 5: Python-FileIO

File I/OIntroduction

Declaration

def load_numbers(numbers, filename): pass

def save_numbers(numbers, filename): pass

Fill them!

Page 6: Python-FileIO

File I/OIntroduction

Two New Functions• Load Numbers

• Save Numbers

Variable File

Variable File

Page 7: Python-FileIO

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.....

Page 8: Python-FileIO

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

Page 9: Python-FileIO

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()

Page 10: Python-FileIO

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”

Page 11: Python-FileIO

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()

Page 12: Python-FileIO

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”

Page 13: Python-FileIO

File I/OIntroduction

Finish

• Finish Code: goo.gl/DDK7d

• Practice by yourself