Python-FileIO

914 views

Published on

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

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
914
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
20
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Python-FileIO

    1. 1. File I/O Python Built-in Data Type NCCU Computer Science Dept. Python Programming for Non-Programmer
    2. 2. Recall & Warn Upname = open(‘filename’, ‘w’)read()readline()readlines()write()writelines() File I/O Introduction
    3. 3. Get The Source• goo.gl/18AIo• Finish the code by yourself! File I/O Introduction
    4. 4. Declarationdef load_numbers(numbers, filename): passdef save_numbers(numbers, filename): pass File I/O Introduction
    5. 5. Declarationdef load_numbers(numbers, filename): passdef save_numbers(numbers, filename): pass Fill them! File I/O Introduction
    6. 6. Two New Functions• Load Numbers Variable File• Save Numbers Variable File File I/O Introduction
    7. 7. File FormatShould 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. 8. Load NumbersFirst, declare the file object and the close method of the filedef load_numbers(numbers, filename): in_file = open(filename, "rt") # do something... in_file.close() File I/O Introduction
    9. 9. 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/O Introduction
    10. 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. 11. 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/O Introduction
    12. 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
    13. 13. Finish• Finish Code: goo.gl/DDK7d• Practice by yourself File I/O Introduction

    ×