Accessing Files in Python Learning Objectives Concepts about files - - PowerPoint PPT Presentation

accessing files in python learning objectives
SMART_READER_LITE
LIVE PREVIEW

Accessing Files in Python Learning Objectives Concepts about files - - PowerPoint PPT Presentation

Accessing Files in Python Learning Objectives Concepts about files in Python How to open files Different ways of reading files How to write out files How to read then search, count, etc. on files Concepts about


slide-1
SLIDE 1

Accessing Files in Python

slide-2
SLIDE 2

CS 6452: Prototyping Interactive Systems

Learning Objectives

  • Concepts about files in Python
  • How to open files
  • Different ways of reading files
  • How to write out files
  • How to read then search, count, etc. on

files

  • Concepts about exceptions and how to use

try blocks in your code

2

slide-3
SLIDE 3

CS 6452: Prototyping Interactive Systems

Files

  • Lots of data stored in files on your

computer’s disk

  • Want to be able to open those files, read

from them, and write to them

3

slide-4
SLIDE 4

CS 6452: Prototyping Interactive Systems

Types of Files

  • Two main types

− Text (ASCII or Unicode) We’ll use − Binary

  • Text files can be opened in Sublime or

NotePad and it will make sense. Binary won’t.

4

slide-5
SLIDE 5

CS 6452: Prototyping Interactive Systems

Sequential Access

  • We will work with files in a sequential

access mode

− Think of the file as one long sequence of characters − To read something at the end, must read all the prior stuff first − Like a cassette tape, not a CD

5

slide-6
SLIDE 6

CS 6452: Prototyping Interactive Systems

Main Process

  • 1. Open the file

− Output: Often are creating the file − Input: Reading data from it

  • 2. Process the file

− Either read or write

  • 3. Close the file

6

slide-7
SLIDE 7

CS 6452: Prototyping Interactive Systems

Opening a file

7

file_var = open(filename, mode) filename – string specifying the name of the file mode – string specifying mode in which file will be opened

Modes

‘r’ – reading only ‘w’ – writing. If file already exists, erase it. If file doesn’t


exist, create it.

‘a’ – append style writing. If file already exists, all written


data will be put at end. If doesn’t exist, create it.

slide-8
SLIDE 8

CS 6452: Prototyping Interactive Systems

Examples

8

f1 = open("orders.txt", "r") f2 = open("new_work.txt", "w")

slide-9
SLIDE 9

CS 6452: Prototyping Interactive Systems

File Functions/Methods

9

file.read() – Reads the whole file as one big string file.readlines() – Reads whole file into a list where


each element is a single line You can only use those two once for an open file

file.write(somestring) – Writes somestring to the 


file

file.close() – Closes the file. Good form to do it.


If you were writing, it insures that all data does
 go out to the file.

slide-10
SLIDE 10

CS 6452: Prototyping Interactive Systems

Reading a File

10

All at once method def main(): infile = open("example.txt", "r") contents = infile.read() infile.close() print(contents) main()

slide-11
SLIDE 11

CS 6452: Prototyping Interactive Systems

Reading a File

11

Line-by-line method 1 def main(): infile = open("example.txt", "r") for line in infile: print(line) infile.close() main()

slide-12
SLIDE 12

CS 6452: Prototyping Interactive Systems

Reading a File

12

Line-by-line method 2 def main(): infile = open("example.txt", "r") line = infile.readline() while line != '': print(line) line = infile.readline() infile.close() main()

slide-13
SLIDE 13

CS 6452: Prototyping Interactive Systems

Writing a File

13

def main(somestring):

  • utfile = open("example2.txt", "w")
  • utfile.write("Line 1\n")
  • utfile.write(somestring + '\n')
  • utfile.close()

main("Woo hoo")

slide-14
SLIDE 14

CS 6452: Prototyping Interactive Systems

Searching a File

14

def main(): infile = open("mailfile.txt", "r") for line in infile: line = line.lstrip() if not line.startswith("From:"): continue if line.find("@gatech.edu") != -1: print(line) elif line.find("@cc.gatech.edu") != -1: print(line) infile.close() main()

Print lines with "From:" and a gatech address

slide-15
SLIDE 15

CS 6452: Prototyping Interactive Systems

Counting Things

15

def counter(filename): infile = open(filename, "r") data = infile.read() return len(data), len(data.split()), len(data.splitlines())

Count the number of characters, words, and lines in a file Not a good idea if the file is big

slide-16
SLIDE 16

CS 6452: Prototyping Interactive Systems

Counting Things

16

def counter(filename): infile = open(filename, "r") num_chars, num_words, num_lines = 0, 0, 0 for line in infile: num_chars += len(line) num_words += len(line.split()) num_lines += 1 return num_chars, num_words, num_lines

Count the number of characters, words, and lines in a file
 (OK if the file is big)

slide-17
SLIDE 17

CS 6452: Prototyping Interactive Systems

Exceptions

  • Error that occurs while a program is

running, causing execution to halt

  • Want to have some way of anticipating

them in key "risky" spots in program, then recovering and continuing on if a suspected problem actually does arise

17

slide-18
SLIDE 18

CS 6452: Prototyping Interactive Systems

Example

18

def main(): num1 = eval(input('Enter a number: ')) num2 = eval(input("Enter another number: ')) result = num1/num2 print(num1,"/",num2, " is ",result) main()

How handle this? if-then-else

slide-19
SLIDE 19

CS 6452: Prototyping Interactive Systems

Another Example

19

def main(): filename = input('Enter a filename: ') infile = filename.open(filename, 'r') contents = infile.read() print(contents) infile.close() main()

What's the potential problem?

slide-20
SLIDE 20

CS 6452: Prototyping Interactive Systems

Handling Exceptions

  • Use an exception handler
  • Embed "risky" code in a special block

− try

  • Tell the system what to do in case a

problem occurs

− except

20

slide-21
SLIDE 21

CS 6452: Prototyping Interactive Systems

Details

21

try: stat1 stat2 … except ExceptName: stat1 stat2 …

Semantics

  • If not exception occurs in try block, then resume


execution after all statements in except block

  • If a statement in the try block generates an 


exception specified by ExceptName, then the 
 statements in the except block are executed. 
 After they're done, execution goes to following 
 code.

  • If code in try block generates an exception not


specified by the named exception, then the 
 program halts with an error message

Sample ExceptName: IOError, ValueError, … OK to have except: with no ExceptName (catch all)

slide-22
SLIDE 22

CS 6452: Prototyping Interactive Systems

Example

22 def main(): total = 0.0 try: infile = open('sales_data.txt', 'r') for line in infile: amount = float(line) total += amount infile.close() print('Total: $%.2f' % total) except IOError: print('An error occurred trying to read the file.') except ValueError: print('Non-numeric data found in the file.') except: print('An error occurred.') print("Code after try-except") main()

slide-23
SLIDE 23

CS 6452: Prototyping Interactive Systems

Programming Challenge

23

Get a filename from the user and read in that file. Print out all the unique words (tokens) that appear
 in the file, in alphabetical order, with a count of how


  • ften each occurs.
slide-24
SLIDE 24

CS 6452: Prototyping Interactive Systems

Learning Objectives

  • Concepts about files in Python
  • How to open files
  • Different ways of reading files
  • How to write out files
  • How to read then search, count, etc. on

files

  • Concepts about exceptions and how to use

try blocks in your code

24

slide-25
SLIDE 25

CS 6452: Prototyping Interactive Systems

Next Time

  • Prototyping

− All about prototyping, different methods, low

  • vs. high, tools, etc.

25

slide-26
SLIDE 26

CS 6452: Prototyping Interactive Systems

Reading Summary

  • Read article
  • Write a one page (front, 2-3 paragraphs

summary of paper)

  • At bottom of page, write one "interesting

quote" taken from paper

  • Rudd, et al, "Prototyping Debate",

interactions, Jan '96.

26