Introduction to programming using Python

Similar documents
Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

Algorithms and Programming

Twitter and While Loops. April

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

Accessing Web Files in Python

Python File Modes. Mode Description. Open a file for reading. (default)

File Processing. CS 112: Introduction to Programming: File Processing Sequence. File Processing. File IO

CS Programming Languages: Python

Introduction to python

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Introduction to Computer Programming for Non-Majors

LECTURE 4 Python Basics Part 3

FILE HANDLING AND EXCEPTIONS

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

Files on disk are organized hierarchically in directories (folders). We will first review some basics about working with them.

Introduction to Computer Programming for Non-Majors

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Exceptions CS GMU

Python Programming: An Introduction to Computer Science

Exception Handling. Genome 559

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

Text Data, File I/O, and Exceptions

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

#11: File manipulation Reading: Chapter 7

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

File processing and decision structures

CIS192 Python Programming

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

CIS192 Python Programming

Python Tutorial. Day 2

examples from first year calculus (continued), file I/O, Benford s Law

Downloading Tweet Streams and Parsing

Spring 2011 PROGRAMMING ASSIGNMENT Encrypted Message Program Due Tuesday, May 17th

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Pemrograman Jaringan Web Client Access PTIIK

Fundamentals of Programming (Python) Getting Started with Programming

MEIN 50010: Python Flow Control

Introduction to Computer Programming for Non-Majors

Getting Started with Python

CIS192 Python Programming

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

Exceptions. Exceptions. Can have multiple except suites and/or one unnamed except suite

Control Structures 1 / 17

File I/O, Benford s Law, and sets

PROGRAMMING, DATA STRUCTURES AND ALGORITHMS IN PYTHON

Class extension and. Exception handling. Genome 559

Chapter 9: Dealing with Errors

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

MongoDB. Database Initialization. Note

Principles of Computer Science I

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

ECS Baruch Lab 9 Spring 2019 Name

APT Session 2: Python

Loop structures and booleans

Table of Contents EVALUATION COPY

Class extension and. Exception handling. Genome 559

COMP 204: Sets, Commenting & Exceptions

Exam 1, Form A CSE 231 Fall 2012 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Reading and writing files

Files. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Abstract Data Types Chapter 1

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Introduction to Computer Programming for Non-Majors

Slide Set 15 (Complete)

Introduction to Python

A Little Python Part 2

Using Web Services. Chapter 13. Python for Informatics: Exploring Information

Computer Science 217

20.5. urllib Open arbitrary resources by URL

Files. Reading from a file

Advanced Python. Executive Summary, Session 1

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Python Programming: An Introduction to Computer Science

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

COMP 204: Sets, Commenting & Exceptions

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

CSE 115. Introduction to Computer Science I

Introduction to computers and Python. Matthieu Choplin

Introduction to Computer Programming for Non-Majors

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Introduction to Computer Programming for Non-Majors

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Exercise: The basics - variables and types

Fundamentals of Programming (Python) File Processing. Ali Taheri Sharif University of Technology Spring 2018

Exceptions and File I/O

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Outline. gzip and gunzip data compression archiving files and pipes in Unix. format conversions encrypting text

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Introduction to Computer Programming for Non-Majors

Network Programming in Python. What is Web Scraping? Server GET HTML

Creating Extensions for Safari

MULTIPLE CHOICE. Chapter Seven

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Web Clients and Crawlers

Finishing Regular Expressions & XML / Web Scraping

Transcription:

Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 6-2 1

Objectives To open a file, read/write data from/to a file To use file dialogs for opening and saving data To read data from a Web resource To handle exceptions using the try/except/finally clauses To raise exceptions using the raise statements To become familiar with Python s built-in exception classes To access exception object in the handler 2

Open a File We create a file object with the following syntax: file = open(filename, mode) Mode r Description Open a file for reading only r+ Open a file for both reading and writing w a rb wb Open a file for writing only Open a file for appending data. Data are written to the end of the file Open a file for reading binary data Open a file for writing binary data 3

Write to a File: Example Program that creates a file if it does not exist (an existing file with the same name will be erased) and write in it: def main(): # Open file for output outfile = open("python_projects.txt", "w") # Write data to the file outfile.write("django\n") outfile.write("flask\n") outfile.write("ansible") outfile.close() # Close the output file main() # Call the main function 4

Testing File Existence import os.path if os.path.isfile("python_projects.txt"): print("python_projects.txt exists") 5

Read from a File: Example After a file is opened for reading data, you can use: the read(size) method to read a specified number of characters or all characters, the readline() method to read the next line the readlines() method to read all lines into a list. 6

Read from a File: Example with read() def main(): # Open file for input infile = open("python_projects.txt", "r") print("using read(): ") print(infile.read()) infile.close() # Close the input file main() # Call the main function 7

Read from a File: Example with read(size) def main(): infile = open("python_projects.txt", "r") print("\nusing read(number): ") s1 = infile.read(4) # read till the 4th character print(s1) s2 = infile.read(10) # read from 4th till 4th+10th print(repr(s2)) # a new line is also a character \n infile.close() # Close the input file main() # Call the main function 8

Read from a File: Example with readline() def main(): infile = open("python_projects.txt", "r") print("\nusing readline(): ") line1 = infile.readline() line2 = infile.readline() line3 = infile.readline() line4 = infile.readline() print(repr(line1)) print(repr(line2)) print(repr(line3)) print(repr(line4)) infile.close() # Close the input file main() # Call the main function 9

Read from a File: Example with readlines() def main(): # Open file for input infile = open("python_projects.txt", "r") print("\n(4) Using readlines(): ") print(infile.readlines()) # a list of lines infile.close() # Close the input file main() # Call the main function 10

Append Data to a File You can use the 'a' mode to open a file for appending data to an existing file. def main(): # Open file for appending data outfile = open("info.txt", "a") outfile.write("\npython is interpreted\n") outfile.close() # Close the input file main() # Call the main function 11

Writing/Reading Numeric Data To write numbers, convert them into strings, and then use the write method to write them to a file. In order to read the numbers back correctly, you should separate the numbers with a whitespace character such as " " (empty string) or '\n' (new line). 12

Writing/Reading Numeric Data: Example from random import randint def main(): # Open file for writing data outfile = open("numbers.txt", "w") for i in range(10): outfile.write(str(randint(0, 9)) + " ") outfile.close() # Close the file # Open file for reading data infile = open("numbers.txt", "r") s = infile.read() numbers = [int(x) for x in s.split()] for number in numbers: print(number, end = " ") infile.close() # Close the file main() # Call the main function 13

Exercise Write a program that prompts the user to enter a file and counts the number of occurrences of each letter in the file regardless of case. Only take the characters of the alphabet, you can get them with the following from string import ascii_lowercase print(ascii_lowercase) # abcdefghijklmnopqrstuvwxyz 14

Solution 15

Case Studies: Occurrences of Words This case study writes a program that counts the occurrences of words in a text file and displays the words and their occurrences in alphabetical order of words. The program uses a dictionary to store an entry consisting of a word and its count. For each word, check whether it is already a key in the dictionary. If not, add to the dictionary an entry with the word as the key and value 1. Otherwise, increase the value for the word (key) by 1 in the dictionary See the program CountOccurenceOfWords.py 16

Retrieving Data from the Web Using Python, you can write simple code to read data from a Website. All you need to do is to open a URL link using the urlopen function as follows: import urllib.request infile = urllib.request.urlopen('http://example.org/') html_page = infile.read().decode() print(html_page) It represents the full HTML of the page just as a web browser would see it 17

Exercise Count each letter from a web page (from the source code of the page) You can reuse the code of the previous and try to refactor so that both programs use the same count_letter function 18

Solution 19

Exception Handling What happens if the user enters a file or an URL that does not exist? The program would be aborted and raises an error. For example, if you run count_letter.py with an incorrect input: c:\session6\python count_letter.py Enter a filename: non_existant_file.txt Traceback (most recent call last): File "path_to/count_letter.py", line 18, in <module> main() File "path_to/count_letter.py", line 7, in main f = open(filename) FileNotFoundError: [Errno 2] No such file or directory: 'non_existant_file.txt' Process finished with exit code 1 20

Catching one exception type try: <body> except <ExceptionType>: <handler> The try... except clause 21

The try... except clause Catching several exception types try: <body> except <ExceptionType>: <handler1> <handler1>... except <ExceptionTypeN>: <handlern> except: <handlerexcept> else: <process_else> # will be executed if not exception finally: <process_finally> # executed with or without exception 22

Example def main(): try: number1, number2 = int( input("enter two integers," "separated by a comma: ")) result = number1 / number2 print("result is " + str(result)) except ZeroDivisionError: print("division by zero!") except SyntaxError: print("a comma may be missing in the input") except: print("something wrong in the input") else: print("no exceptions") finally: print("the finally clause is executed") main() 23

Raising Exceptions You learned how to write the code to handle exceptions in the preceding section. Where does an exception come from? How is an exception created? Exceptions are objects and objects are created from classes. An exception is raised from a function. When a function detects an error, it can create an object of an appropriate exception class and raise the object, using the following syntax: raise ExceptionClass("Something is wrong") 24

Processing Exceptions Using Exception Objects You can access the exception object in the except clause with the as keyword. try: number = int(input("enter a number: ")) print("the number entered is", number) except NameError as ex: print("exception:", ex) 25

Using the with statement It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent tryfinally blocks: with open('python_projects.txt', 'r') as f: read_data = f.read() assert f.closed 26

The json file format json (Javascript Object Notation) is a lightweight data interchange format with which you: dump data ("serialize") load data ("deserialize") import json serialized_data = json.dumps( ['foo', {'bar': ('baz', None, 1.0, 2)}]) print(serialized_data) deserialized_data = json.loads(serialized_data) print(deserialized_data) 27

Example with a simple rest API (1) How to get the capital of each country? import json from urllib import request infile = request.urlopen( 'https://restcountries.eu/rest/v1/all') content_as_python_obj = json.loads(infile.read().decode()) for country in content_as_python_obj: print(country['borders']) Can you see what object is the "borders"? 28

Example with a simple rest API (2) import json from urllib import request infile = request.urlopen( 'https://restcountries.eu/rest/v1/all') content_as_python_obj = json.loads(infile.read().decode()) for country in content_as_python_obj: print(country['capital']) 29

API In the previous case, an API (Application Programming Interface) is simply a specification of remote calls exposed to the API consumers We are using the API as a service by just calling (doing a GET) its available urls 30

Example with the Google map API from urllib import parse, request import json serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?' while True: address = input('enter location (q to quit): ') if len(address) < 1 or address.lower() == 'q': # sentinel value, press q to quit break url = serviceurl + parse.urlencode({'sensor': 'false', 'address': address}) print('retrieving', url) uh = request.urlopen(url) data = uh.read().decode('utf-8') print('retrieved', len(data), 'characters') js = json.loads(data) if 'status' not in js or js['status']!= 'OK': print('==== Failure To Retrieve ====') print(data) continue lat = js["results"][0]["geometry"]["location"]["lat"] lng = js["results"][0]["geometry"]["location"]["lng"] print('lat', lat, 'lng', lng) location = js['results'][0]['formatted_address'] print(location) 31

Example with the Twitter API using the client Tweepy 1. Navigate to https://apps.twitter.com/ 2. Click the button to create a new application 3. Enter dummy data 4. Once the application is created, get the following: consumer_key consumer_secret access_token access_secret 32

Get tweet with #python import tweepy consumer_key = 'get_your_own' consumer_secret = 'get_your_own' access_token = 'get_your_own' access_secret = 'get_your_own' def main(): auth = tweepy.auth.oauthhandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.api(auth) tweets = api.search(q='#python') for t in tweets: print(t.created_at, t.text, '\n') main() 33