Introduction to Computing Using Python Text Data, File I/O, and Exceptions  Strings, revisited  Formatted output  File Input/Output  Errors and Exceptions.

Slides:



Advertisements
Similar presentations
Perkovic, Chapter 7 Functions revisited Python Namespaces
Advertisements

CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Introduction to Computing Using Python Methods – on strings and other things  Strings, revisited  Objects and their methods  Indexing and slicing 
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Introduction to Computing Using Python Text Data, File I/O, and Exceptions  Strings, revisited  Formatted output  File Input/Output  Errors and Exceptions.
Introduction to Computing Using Python File I/O  File Input/Output  read(), readline(), readlines()  Writing to a file.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Introduction to C Programming
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Python Data Types Expressions, Variables, and Assignments Strings
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Introduction to Computing Using Python Python  Python is an interactive language.  Java or C++: compile, run  Also, a main function or method  Python:
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Built-in Data Structures in Python An Introduction.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
LECTURE 5 Strings. STRINGS We’ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type. Strings are.
Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
28 Formatted Output.
CSc 120 Introduction to Computer Programing II Adapted from slides by
CSc 120 Introduction to Computer Programing II Adapted from slides by
File I/O File input/output Iterate through a file using for
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
CS 100: Roadmap to Computing
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CSc 120 Introduction to Computer Programing II
Exceptions and File Input
Introduction to Scripting
Exceptions and files Taken from notes by Dr. Neil Moore
Python Data Types Expressions, Variables, and Assignments Strings
Methods – on strings and other things
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
INPUT & OUTPUT scanf & printf.
File I/O File input/output Iterate through a file using for
Exceptions and files Taken from notes by Dr. Neil Moore
File I/O File input/output Iterate through a file using for
CS 100: Roadmap to Computing
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Fundamentals of Python: First Programs
CS190/295 Programming in Python for Life Sciences: Lecture 3
Methods – on strings and other things
CHAPTER 3: String And Numeric Data In Python
Introduction to Java Applications
15-110: Principles of Computing
Introduction to Computer Science
Topics Introduction to File Input and Output
CS 100: Roadmap to Computing
Presentation transcript:

Introduction to Computing Using Python Text Data, File I/O, and Exceptions  Strings, revisited  Formatted output  File Input/Output  Errors and Exceptions

Introduction to Computing Using Python String representations >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick" >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick" >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick” >>> excuse = 'I\'m...\n... "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick” >>> excuse = 'I\'m...\n... "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick” >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick” >>> excuse = 'I\'m...\n... "sick"' >>> excuse 'I\'m...\n... "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick” >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick” >>> excuse = 'I\'m...\n... "sick"' >>> excuse 'I\'m...\n... "sick"' >>> >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick” >>> excuse = 'I\'m...\n... "sick"' >>> excuse 'I\'m...\n... "sick"' >>> print(excuse) I'm "sick" >>> excuse = 'I am sick' >>> excuse = "I am sick" >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> excuse = "I'm sick" >>> excuse = "I'm "sick"" SyntaxError: invalid syntax >>> excuse = 'I'm "sick"' SyntaxError: invalid syntax >>> excuse = 'I\'m "sick"' >>> excuse 'I\'m "sick"' >>> print(excuse) I'm "sick” >>> excuse = 'I\'m...\n... "sick"' >>> excuse 'I\'m...\n... "sick"' >>> print(excuse) I'm "sick" A string value is represented as a sequence of characters delimited by quotes Quotes can be single ( ' ) or double ( " ) What if ' or " is one of the string characters? What if the string includes both ' and " ? Escape sequence \' or \" is used to indicate that a quote is not the string delimiter but is part of the string value Function print() interprets the escape sequence Another example: \n is an escape sequence that represents a new line

The indexing operator returns the character at index i (as a single character string). Introduction to Computing Using Python Indexing operator, revisited 'A' 'p' 'l' 'e' s[0] = s[1] = s[2] = s[3] = s[4] = s = >>> s = 'Apple' >>> s[0] 'A' >>> s[1] 'p' >>> s[4] 'e' >>> s = 'Apple' >>> s[0] 'A' >>> s[1] 'p' >>> s[4] 'e' 'A p p l e' s[0:2] = 'A p' s[1:4] = 'p p l' s[2:5] = 'p l e' s[2:] = 'p l e' s[-3:-1] = 'p l' s[:2] = 'A p' >>> s = 'Apple' >>> s[0:2] 'Ap' >>> s[1:4] 'ppl' >>> s[2:5] 'ple' >>> s[2:] 'ple' >>> s[:2] 'Ap' >>> s[-3:-1] 'pl' >>> s = 'Apple' >>> s[0:2] 'Ap' >>> s[1:4] 'ppl' >>> s[2:5] 'ple' >>> s[2:] 'ple' >>> s[:2] 'Ap' >>> s[-3:-1] 'pl' The indexing operator can also be used to obtain a slice of a string s[i:j] : the slice of s starting at index i and ending before index j s[i:] : the slice of s starting at index i s[:j] : the slice of s ending before index j

Introduction to Computing Using Python Exercise The indexing operator can also be used to obtain slices of a list as well. Let list lst refer to list ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h’] Write Python expressions using list lst and the indexing operator that evaluate to: a)['a', 'b', 'c', 'd'] b)['d', 'e', 'f'] c)['d'] d)['f', 'g'] e)['d', 'e', 'f', 'g’, 'h'] f)['f', 'g', 'h'] >>> lst[:4] ['a', 'b', 'c', 'd'] >>> lst[3:6] ['d', 'e', 'f'] >>> lst[3:4] ['d'] >>> lst[-3:-1] ['f', 'g'] >>> lst[3:] ['d', 'e', 'f', 'g’, 'h'] >>> lst[-3:] ['f', 'g', 'h'] >>> lst[:4] ['a', 'b', 'c', 'd'] >>> lst[3:6] ['d', 'e', 'f'] >>> lst[3:4] ['d'] >>> lst[-3:-1] ['f', 'g'] >>> lst[3:] ['d', 'e', 'f', 'g’, 'h'] >>> lst[-3:] ['f', 'g', 'h']

UsageExplanation s.capitalize() returns a copy of s with first character capitalized s.count(target) returns the number of occurences of target in s s.find(target) returns the index of the first occurrence of target in s s.lower() returns lowercase copy of s s.replace(old, new) returns copy of s with every occurrence of old replaced with new s.split(sep) returns list of substrings of s, delimited by sep s.strip() returns copy of s without leading and trailing whitespace s.upper() returns lowercase copy of s Introduction to Computing Using Python String methods >>> link = ' >>> link[:4] 'http' >>> link[:4].upper() 'HTTP' >>> link.find('smith') 20 >>> link[20:25] 'smith' >>> link[20:25].capitalize() 'Smith' >>> link.replace('smith', ‘jones’) ' >>> link ' >>> new = link.replace('smith', ‘jones') >>> new ' >>> link.count('/') 4 >>> link.split('/') [' '', ' 'smith', 'index.html'] >>> link = ' >>> link[:4] 'http' >>> link[:4].upper() 'HTTP' >>> link.find('smith') 20 >>> link[20:25] 'smith' >>> link[20:25].capitalize() 'Smith' >>> link.replace('smith', ‘jones’) ' >>> link ' >>> new = link.replace('smith', ‘jones') >>> new ' >>> link.count('/') 4 >>> link.split('/') [' '', ' 'smith', 'index.html'] Strings are immutable; none of the string methods modify string link Strings are immutable; none of the string methods modify string s

Introduction to Computing Using Python Exercise >>> events = '9/13 2:30 PM\n9/14 11:15 AM\n9/14 1:00 PM\n9/15 9:00 AM' >>> print(events) 9/13 2:30 PM 9/14 11:15 AM 9/14 1:00 PM 9/15 9:00 AM >>> events = '9/13 2:30 PM\n9/14 11:15 AM\n9/14 1:00 PM\n9/15 9:00 AM' >>> print(events) 9/13 2:30 PM 9/14 11:15 AM 9/14 1:00 PM 9/15 9:00 AM >>> events.count('9/14') 2 >>> events.find('9/14') 13 >>> events.find('9/15') 40 >>> events[13:40] '9/14 11:15 AM\n9/14 1:00 PM\n’ >>> lst = events[13:40].strip().split('\n') >>> lst ['9/14 11:15 AM', '9/14 1:00 PM'] >>> >>> events.count('9/14') 2 >>> events.find('9/14') 13 >>> events.find('9/15') 40 >>> events[13:40] '9/14 11:15 AM\n9/14 1:00 PM\n’ >>> lst = events[13:40].strip().split('\n') >>> lst ['9/14 11:15 AM', '9/14 1:00 PM'] >>> Write expressions that compute: a)the number of events on 9/14 b)the index of the substring describing the 1 st event on 9/14 c)the index just past the substring describing the last event on 9/14 d)the list of substrings describing the events on 9/14 String events describes the schedule of 4 events spread across 3 days

UsageExplanation str.maketrans(old, new) returns a table mapping characters in string old to characters in string new s.translate(table) returns a copy of s in which the original characters are replaced using the mapping described by table Introduction to Computing Using Python String methods >>> event = "Tuesday, Feb 29, :35 PM" >>> >>> event = "Tuesday, Feb 29, :35 PM" >>> Suppose we need to pick up the date and time components of string event >>> event = "Tuesday, Feb 29, :35 PM" >>> table = str.maketrans(':,-', 3*' ') >>> event.translate(table) 'Tuesday Feb PM' >>> >>> event = "Tuesday, Feb 29, :35 PM" >>> table = str.maketrans(':,-', 3*' ') >>> event.translate(table) 'Tuesday Feb PM' >>> >>> event = "Tuesday, Feb 29, :35 PM" >>> table = str.maketrans(':,-', 3*' ') >>> event.translate(table) 'Tuesday Feb PM' >>> event.translate(table).split() ['Tuesday', 'Feb', '29', '2012', '3', '35', 'PM'] >>> >>> event = "Tuesday, Feb 29, :35 PM" >>> table = str.maketrans(':,-', 3*' ') >>> event.translate(table) 'Tuesday Feb PM' >>> event.translate(table).split() ['Tuesday', 'Feb', '29', '2012', '3', '35', 'PM'] >>> Puntuation makes it difficult to use method split() Solution: replace punctuation with blank spaces

Introduction to Computing Using Python Exercise Read a line of text Use translation table to: replace each ' ' with '\n', and capitalize every vowel (and then print)

Introduction to Computing Using Python Files and the file system / / Applications Users bin var Firefox.app Mail.app Shared messi poem.txt image.jpg Contents MacOS Mail Canon The file system is the Operating System(OS) component that organizes files and provides a way to create, access, and modify files Files are organized into a tree structure root folder / / Applications Users bin var Firefox.app Mail.app Shared messi Contents MacOS Canon folders (or directories) regular files text filebinary file While every file and folder has a name, it is the file pathname that identifies the file poem.txt Absolute pathnames /var/poem.txt /Users/messi/poem.txt /Applications/Mail.app/ Relative pathnames (relative to current working directory Users ) messi/poem.txt messi/image.jpg Shared

Introduction to Computing Using Python Opening and closing a file Processing a file consists of: 1.Opening the file 2.Reading from and/or writing to the file 3.Closing the file >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> infile = open('example.txt', 'r') >>> >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> infile = open('example.txt', 'r') >>> >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> infile = open('example.txt', 'r') >>> infile.close() >>> >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> infile = open('example.txt', 'r') >>> infile.close() >>> Built-in function open() is used to open a file The second (optional) argument is the file mode The first input argument is the file pathname, whether absolute or relative with respect to the current working directory File mode 'r' is used to open a file for reading (rather than, say, writing) A “file” object is of a type that supports several “file” methods, including method close() that closes the file Returns a “file” object

Introduction to Computing Using Python Open file mode ModeDescription r Reading (default) w Writing (if file exists, content is wiped) a Append (if file exists, writes are appended) r+ Reading and Writing t Text (default) b Binary The file mode defines how the file will be accessed >>> infile = open('example.txt', 'rt') >>> infile = open('example.txt', 'r') >>> infile = open('example.txt', 't') >>> infile = open('example.txt') >>> infile = open('example.txt', 'rt') >>> infile = open('example.txt', 'r') >>> infile = open('example.txt', 't') >>> infile = open('example.txt') These are all equivalent

Introduction to Computing Using Python File methods UsageDescription infile.read(n) Read n characters starting from cursor; if fewer than n characters remain, read until the end of file infile.read() Read starting from cursor up to the end of the file infile.readline() Read starting from cursor up to, and including, the end of line character infile.readlines() Read starting from cursor up to the end of the file and return list of lines outfile.write(s) Write string s to file outfile starting from cursor infile.close(n) Close file infile There are several “file” types; they all support similar “file” methods Methods read() and readline() return the characters read as a string Methods readlines() returns the characters read as a list of lines Method write() returns the number of characters written

Introduction to Computing Using Python Reading a file >>> infile = open('example.txt') >>> >>> infile = open('example.txt') >>> 1 The 3 lines in this file end with the new line character.\n 2 \n 3 There is a blank line above this line.\n 1 The 3 lines in this file end with the new line character.\n 2 \n 3 There is a blank line above this line.\n ⌃⌃⌃ ⌃ ⌃ >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' >>> infile.read() '\nThere is a blank line above this line.\n' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' >>> infile.read() '\nThere is a blank line above this line.\n' >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' >>> infile.read() '\nThere is a blank line above this line.\n' >>> infile.close() >>> >>> infile = open('example.txt') >>> infile.read(1) 'T' >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' >>> infile.read() '\nThere is a blank line above this line.\n' >>> infile.close() >>> example.txt When the file is opened, a cursor is associated with the opened file The initial position of the cursor is: at the beginning of the file, if file mode is r at the end of the file, if file mode is a or w

Introduction to Computing Using Python Patterns for reading a text file def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content) def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content) Common patterns for reading a file: 1.Read the file content into a string 2.Read the file content into a list of words 3.Read the file content into a list of lines def numWords(filename): 'returns the number of words in file filename' infile = open(filename) content = infile.read() infile.close() wordList = content.split() return len(wordList) def numWords(filename): 'returns the number of words in file filename' infile = open(filename) content = infile.read() infile.close() wordList = content.split() return len(wordList) def numLines(filename): 'returns the number of lines in file filename' infile = open(filename, 'r’) lineList = infile.readlines() infile.close() return len(lineList) def numLines(filename): 'returns the number of lines in file filename' infile = open(filename, 'r’) lineList = infile.readlines() infile.close() return len(lineList) Example:

T2341 T234 1 T2341 T234 1 This is the first line This is the first line This is the first line. Still the first line…\n This is the first line. Still the first line…\n This is the first line. Still the first line…\n 2 Now we are in the second line.\n This is the first line. Still the first line…\n 2 Now we are in the second line.\n This is the first line. Still the first line…\n 2 Now we are in the second line.\n 3 Non string value like 5 must be converted first.\n 4 1 This is the first line. Still the first line…\n 2 Now we are in the second line.\n 3 Non string value like 5 must be converted first.\n 4 1 This is the first line. Still the first line…\n 2 Now we are in the second line.\n 3 Non string value like 5 must be converted first.\n 4 Non string value like 5 must be converted first.\n 1 This is the first line. Still the first line…\n 2 Now we are in the second line.\n 3 Non string value like 5 must be converted first.\n 4 Non string value like 5 must be converted first.\n Introduction to Computing Using Python Writing to a text file ⌃⌃ ⌃ ⌃ ⌃ >>> outfile = open('test.txt', 'w') >>> >>> outfile = open('test.txt', 'w') >>> test.txt ⌃⌃ >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') 31 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') 31 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') 31 >>> outfile.write('Non string value like '+str(5)+' must be converted first.\n') 49 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') 31 >>> outfile.write('Non string value like '+str(5)+' must be converted first.\n') 49 >>> >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') 31 >>> outfile.write('Non string value like '+str(5)+' must be converted first.\n') 49 >>> outfile.write('Non string value like {} must be converted first.\n'.format(5)) 49 >>> outfile.close() >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') 31 >>> outfile.write('Non string value like '+str(5)+' must be converted first.\n') 49 >>> outfile.write('Non string value like {} must be converted first.\n'.format(5)) 49 >>> outfile.close()

>>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> print(prod, cost, wght, total) morels >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> print(prod, cost, wght, total) morels >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> print(prod, cost, wght, total) morels >>> print(prod, cost, wght, total, sep='; ') morels; 139; 0.5; 69.5 >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> print(prod, cost, wght, total) morels >>> print(prod, cost, wght, total, sep='; ') morels; 139; 0.5; 69.5 >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> print(prod, cost, wght, total) morels >>> print(prod, cost, wght, total, sep='; ') morels; 139; 0.5; 69.5 >>> print(prod, cost, wght, total, sep=':::') morels:::139:::0.5:::69.5 >>> >>> prod = 'morels' >>> cost = 139 >>> wght = 1/2 >>> total = cost * wght >>> print(prod, cost, wght, total) morels >>> print(prod, cost, wght, total, sep='; ') morels; 139; 0.5; 69.5 >>> print(prod, cost, wght, total, sep=':::') morels:::139:::0.5:::69.5 >>> Introduction to Computing Using Python Built-in function print(), revisited Function print() takes 0 or more arguments and prints them in the shell A blank space separator is printed between the arguments The sep argument allows for customized separators their string representation

>>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa cat dog >>> >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa cat dog >>> Introduction to Computing Using Python Built-in function print(), revisited Function print() prints, by default, a newline character after printing its arguments The end argument allows for customized end characters >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa\n cat\n dog\n >>> >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa\n cat\n dog\n >>> >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa cat dog >>> for pet in pets: print(pet, end=', ') boa, cat, dog, >>> >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa cat dog >>> for pet in pets: print(pet, end=', ') boa, cat, dog, >>> >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa cat dog >>> for pet in pets: print(pet, end=', ') boa, cat, dog, >>> for pet in pets: print(pet, end='!!! ') boa!!! cat!!! dog!!! >>> >>> pets = ['boa', 'cat', 'dog'] >>> for pet in pets: print(pet) boa cat dog >>> for pet in pets: print(pet, end=', ') boa, cat, dog, >>> for pet in pets: print(pet, end='!!! ') boa!!! cat!!! dog!!! >>>

Introduction to Computing Using Python General output formatting >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> Suppose we have >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> and we want to print Wednesday, March 10, 2010 at 11:45:33 >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print(str(hour)+':'+str(minute)+':'+str(second)) 11:45:33 >>> >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print(str(hour)+':'+str(minute)+':'+str(second)) 11:45:33 >>> >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print(str(hour)+':'+str(minute)+':'+str(second)) 11:45:33 >>> print('{}:{}:{}'.format(hour, minute, second)) 11:45:33 >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print(str(hour)+':'+str(minute)+':'+str(second)) 11:45:33 >>> print('{}:{}:{}'.format(hour, minute, second)) 11:45:33

Introduction to Computing Using Python Method format() of class str >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print('{}:{}:{}'.format(hour, minute, second)) 11:45:33 >>> >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print('{}:{}:{}'.format(hour, minute, second)) 11:45:33 >>> print('{}:{}:{}'.format(hour, minute, second)) format string >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print('{}:{}:{}'.format(hour, minute, second)) 11:45:33 >>> print('{}, {} {}, {} at {}:{}:{}'.format(weekday, month, day, year, hour, minute, second)) Wednesday, March 10, 2012 at 11:45:33 >>> day = 'Wednesday' >>> month = 'March' >>> weekday = 'Wednesday' >>> month = 'March' >>> day = 10 >>> year = 2010 >>> year = 2012 >>> hour = 11 >>> minute = 45 >>> second = 33 >>> print('{}:{}:{}'.format(hour, minute, second)) 11:45:33 >>> print('{}, {} {}, {} at {}:{}:{}'.format(weekday, month, day, year, hour, minute, second)) Wednesday, March 10, 2012 at 11:45:33 placeholders

Introduction to Computing Using Python Specifying field width The format() method can be used to line up data in columns >>> for i in range(1,8): print(i, i**2, 2**i) >>> >>> for i in range(1,8): print(i, i**2, 2**i) >>> >>> for i in range(1,8): print(i, i**2, 2**i) >>> for i in range(1, 8): print('{} {:2} {:3}'.format(i, i**2, 2**i)) >>> >>> for i in range(1,8): print(i, i**2, 2**i) >>> for i in range(1, 8): print('{} {:2} {:3}'.format(i, i**2, 2**i)) >>> reserves 2 spaces for i**2 reserves 3 spaces for 2**i plus a blank space between the columns Numbers are aligned to the right

Introduction to Computing Using Python Specifying field width >>> lst = ['Alan Turing', 'Ken Thompson', 'Vint Cerf'] >>> for name in lst: fl = name.split() print(fl[0], fl[1]) Alan Turing Ken Thompson Vint Cerf >>> >>> lst = ['Alan Turing', 'Ken Thompson', 'Vint Cerf'] >>> for name in lst: fl = name.split() print(fl[0], fl[1]) Alan Turing Ken Thompson Vint Cerf >>> >>> lst = ['Alan Turing', 'Ken Thompson', 'Vint Cerf'] >>> for name in lst: fl = name.split() print(fl[0], fl[1]) Alan Turing Ken Thompson Vint Cerf >>> for name in lst: fl = name.split() print('{:5} {:10}'.format(fl[0], fl[1])) Alan Turing Ken Thompson Vint Cerf >>> >>> lst = ['Alan Turing', 'Ken Thompson', 'Vint Cerf'] >>> for name in lst: fl = name.split() print(fl[0], fl[1]) Alan Turing Ken Thompson Vint Cerf >>> for name in lst: fl = name.split() print('{:5} {:10}'.format(fl[0], fl[1])) Alan Turing Ken Thompson Vint Cerf >>> Strings are aligned to the left The format() method can be used to line up data in columns

Introduction to Computing Using Python Output format type >>> n = 10 >>> '{:b}'.format(n) '1010' >>> '{:c}'.format(n) '\n' >>> '{:d}'.format(n) '10' >>> '{:X}'.format(n) 'A' >>> '{:e}'.format(n) ' e+01' >>> >>> n = 10 >>> '{:b}'.format(n) '1010' >>> '{:c}'.format(n) '\n' >>> '{:d}'.format(n) '10' >>> '{:X}'.format(n) 'A' >>> '{:e}'.format(n) ' e+01' >>> Inside the curly braces of a placeholder, we can specify the field width TypeExplanation b binary c character d decimal X hexadecimal e scientific f fixed-point >>> n = 10 >>> '{:b}'.format(n) '1010' >>> '{:c}'.format(n) '\n' >>> '{:d}'.format(n) '10' >>> '{:X}'.format(n) 'A' >>> '{:e}'.format(n) ' e+01' >>> '{:7.2f}'.format(n) ' 10.00' >>> >>> n = 10 >>> '{:b}'.format(n) '1010' >>> '{:c}'.format(n) '\n' >>> '{:d}'.format(n) '10' >>> '{:X}'.format(n) 'A' >>> '{:e}'.format(n) ' e+01' >>> '{:7.2f}'.format(n) ' 10.00' >>> '{:7.2f}' field width decimal precision Inside the curly braces of a placeholder, we can specify the field width, the type of the output Inside the curly braces of a placeholder, we can specify the field width, the type of the output, and the decimal precision

Introduction to Computing Using Python Types of errors >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt’ >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File " ", line 1, in print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt') Traceback (most recent call last): File " ", line 1, in infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt’ We saw different types of errors in this chapter There are basically two types of errors: syntax errors erroneous state errors

Introduction to Computing Using Python Syntax errors >>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10): print(i) SyntaxError: expected an indented block >>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10): print(i) SyntaxError: expected an indented block Syntax errors are errors that are due to the incorrect format of a Python statement They occur while the statement is being translated to machine language and before it is being executed.

Introduction to Computing Using Python Erroneous state errors >>> 3/0 Traceback (most recent call last): File " ", line 1, in 3/0 ZeroDivisionError: division by zero >>> 3/0 Traceback (most recent call last): File " ", line 1, in 3/0 ZeroDivisionError: division by zero The program execution gets into an erroneous state >>> lst Traceback (most recent call last): File " ", line 1, in lst NameError: name 'lst' is not defined >>> lst Traceback (most recent call last): File " ", line 1, in lst NameError: name 'lst' is not defined >>> lst = [12, 13, 14] >>> lst[3] Traceback (most recent call last): File " ", line 1, in lst[3] IndexError: list index out of range >>> lst = [12, 13, 14] >>> lst[3] Traceback (most recent call last): File " ", line 1, in lst[3] IndexError: list index out of range >>> lst * lst Traceback (most recent call last): File " ", line 1, in lst * lst TypeError: can't multiply sequence by non-int of type 'list’ >>> lst * lst Traceback (most recent call last): File " ", line 1, in lst * lst TypeError: can't multiply sequence by non-int of type 'list’ >>> int('4.5') Traceback (most recent call last): File " ", line 1, in int('4.5') ValueError: invalid literal for int() with base 10: '4.5' >>> int('4.5') Traceback (most recent call last): File " ", line 1, in int('4.5') ValueError: invalid literal for int() with base 10: '4.5' When an error occurs, an “error” object is created This object has a type that is related to the type of error The object contains information about the error The “error” object is called an exception; the creation of an exception due to an error is called the raising of an exception When an error occurs, an “error” object is created This object has a type that is related to the type of error The object contains information about the error The default behavior is to print this information and interrupt the execution of the statement. >>> int('4.5') Traceback (most recent call last): File " ", line 1, in int('4.5') ValueError: invalid literal for int() with base 10: '4.5' >>> int('4.5') Traceback (most recent call last): File " ", line 1, in int('4.5') ValueError: invalid literal for int() with base 10: '4.5'

Introduction to Computing Using Python Exception types Some of the built-in exception classes: ExceptionExplanation KeyboardInterrupt Raised when user hits Ctrl-C, the interrupt key OverflowError Raised when a floating-point expression evaluates to a value that is too large ZeroDivisionError Raised when attempting to divide by 0 IOError Raised when an I/O operation fails for an I/O-related reason IndexError Raised when a sequence index is outside the range of valid indexes NameError Raised when attempting to evaluate an unassigned identifier (name) TypeError Raised when an operation of function is applied to an object of the wrong type ValueError Raised when operation or function has an argument of the right type but incorrect value