Introduction to python

Similar documents
What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

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

CS Programming Languages: Python

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Exceptions CS GMU

#11: File manipulation Reading: Chapter 7

LECTURE 4 Python Basics Part 3

Exception Handling. Genome 559

Introduction to: Computers & Programming: Exception Handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

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

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559

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

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

CIS192 Python Programming

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file:

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

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

FILE HANDLING AND EXCEPTIONS

MEIN 50010: Python Flow Control

Slide Set 15 (Complete)

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

COMP 204: Sets, Commenting & Exceptions

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

Senthil Kumaran S

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

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Exceptions & error handling in Python 2 and Python 3

Introduction to Computer Programming for Non-Majors

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Chapter 9: Dealing with Errors

MUTABLE LISTS AND DICTIONARIES 4

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

STSCI Python Introduction

CS 11 python track: lecture 2

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

COMP 204: Sets, Commenting & Exceptions

Python. Karin Lagesen.

Introduction to programming using Python

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

1 Strings (Review) CS151: Problem Solving and Programming

An Introduction to Python

Python for Astronomers. Errors and Exceptions

Lecture 17A: Finite and Infinite Iterators

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

Lists How lists are like strings

CS115 - Module 10 - General Trees

Python Tutorial. Day 2

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

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

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Lab 5: File I/O CSE/IT 107. NMT Computer Science

The current topic: Python. Announcements. Python. Python

Files. Reading from a file

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Intro. Scheme Basics. scm> 5 5. scm>

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Exceptions & a Taste of Declarative Programming in SQL

Python for Informatics

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I

Idioms and Anti-Idioms in Python

Lecture #12: Quick: Exceptions and SQL

STSCI Python Introduction. Class URL

Errors. And How to Handle Them

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Algorithms and Programming

CS 112: Intro to Comp Prog

Programming refresher and intro to C programming

Python for Non-programmers

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

Strengthen Your Python Foundations

Introduction to Computer Programming for Non-Majors

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

MULTIPLE CHOICE. Chapter Seven

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Control Structures 1 / 17

Python for C programmers

Directory of C:\Users\Ami\Documents\Python Scripts

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Programming with Python

roboturtle Documentation

1 Lecture 6: Conditionals and Exceptions

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

EXCEPTIONS, CALCULATOR 10

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Final Exam Version A

CS Lecture 26: Grab Bag. Announcements

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

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

CS 111X - Fall Test 1

Level 3 Computing Year 2 Lecturer: Phil Smith

CGI Architecture Diagram. Web browser takes response from web server and displays either the received file or error message.

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


Chapter 6. Files and Exceptions I

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Transcription:

Introduction to python 13 Files Rossano Venturini rossano.venturini@unipi.it

File System A computer s file system consists of a tree-like structured organization of directories and files directory file

File System Each OS has its own restrictions on file names and extensions In Linux, extension does not identifies the kind of file (info in the header of the file) just one root

File System Each OS has its own restrictions on file names and extensions In Linux, extension does not identifies the kind of file (info in the header of the file) file identified by path prog.py /usr/bin/prog.py

File system Current directory Denoted by../prog.py cd path > changes the current directory prog.py

File system Current directory Denoted by../prog.py cd path > changes the current directory Parent directory Denoted by.. cd.. prog.py

Working with files

Working with files File handle: access to file

Working with files operating on the file, moves the file s position

Working with files OS allows a limited number of opened files

Position With the handler, you have access to the current position p in the file p

Position With the handler, you have access to the current position p in the file It is moved according to the operations performed on the file (or positioned manually) p

Buffering Data is not written immediately to file, but first placed in a zone of the memory (buffer) Buffer p

Buffering Data is not written immediately to file, but first placed in a zone of the memory (buffer) OS flushes the buffer when it sees a need for that Flush can be manual p Buffer

Buffering Data is not written immediately to file, but first placed in a zone of the memory (buffer) OS flushes the buffer when it sees a need for that Flush can be manual Because of this mechanism, data might not be on file if your program crashes! p

Text files TXT open(name, [mode]) Opens the file name (either current dir, or complete path) mode is optional (read, write, etc.) Returns the handle h = open( pippo.txt ) open ( pippo.txt ) as h

Text files TXT read() Given a handle, reads the content of the file In its simplest form, returns the complete content of the file as a string Moves the pointer to the end h = open( pippo.txt ) print(h.read()) print(h.read()) What do i get here?

Text files TXT read() Given a handle, reads the content of the file In its simplest form, returns the complete content of the file as a string Moves the pointer to the end h = open( pippo.txt ) print(h.read()) print(h.read()) Second string is empty (pointer moved to end)

Text files TXT close() Closes the file (using its handle), and releases the handle h = open( pippo.txt ) print(h.read()) h.close()

Text files TXT Alternative syntax with open( pippo.txt ) as h: buf = h.read() print(buf) h closed automatically after block

Text files TXT readline() This method reads line by line From current pointer s position up to (and including) next newline h = open( pippo.txt ) while True: buf = h.readline() if buf == : break print(buf) h.close() You will see an empty line after each line.why?

Text files TXT readline() This method reads line by line From current pointer s position up to (and including) next newline h = open( pippo.txt ) while True: buf = h.readline() if buf == : break print(buf) h.close() One empty from the readline() One empty from the print()

Text files TXT readline() This method reads line by line From current pointer s position up to (and including) next newline h = open( pippo.txt ) while True: buf = h.readline() if buf == : break print(buf) h.close() How can you avoid this?

Text files TXT readline() This method reads line by line From current pointer s position up to (and including) next newline h = open( pippo.txt ) while True: buf = h.readline() if buf == : break print(buf, end = ) h.close() Like this!

Text files TXT readlines() Reads all lines, returning them in a list of strings From current pointer s position up to (and including) next newline h = open( pippo.txt ) buf = h.readlines() h.close()

Text files TXT open(name, w ) Opens the file in writing mode If file exists, its content is automatically deleted h = open( pippo.txt, w )

Text files TXT write(string) Given an handle, writes string to the file No newline is added at the end of the string h = open( pippo.txt, w ) h.write( Hello World! )

Text files TXT writelines(string_list) Writes the list of strings to the file No newline is added at the end of each of the strings h = open( pippo.txt, w ) h.writelines([ Hello,, World,! ])

Text files TXT open(name, a ) Opens the file in append mode If file exists, its content is not deleted, and new content is appended at the end h = open( pippo.txt, a )

Text files TXT Useful functions to interact with the file system in the os module getcwd() chdir(new_dir) listdir(dir) system(command) Current working dir

Text files TXT Useful functions to interact with the file system in the os module getcwd() chdir(new_dir) listdir(dir) system(command) Changes dir

Text files TXT Useful functions to interact with the file system in the os module getcwd() chdir(new_dir) listdir(dir) system(command) Returns a list of all file and dirs in dir

Text files TXT Useful functions to interact with the file system in the os module getcwd() chdir(new_dir) listdir(dir) system(command) Executes command (must be supported by the OS)

Text files TXT Useful functions in the os.path module exists(path) isfile(path) isdir(path) dirname(path) getsize(path) Whether file specified by path exists or not

Text files TXT Useful functions in the os.path module exists(path) isfile(path) isdir(path) dirname(path) getsize(path) Whether file specified by path is a file or not

Text files TXT Useful functions in the os.path module exists(path) isfile(path) isdir(path) dirname(path) getsize(path) Whether file specified by path is a dir or not

Text files TXT Useful functions in the os.path module exists(path) isfile(path) isdir(path) dirname(path) getsize(path) Extracts the directory name from a path and returns it

Text files TXT Useful functions in the os.path module exists(path) isfile(path) isdir(path) dirname(path) getsize(path) Returns the size of the file specified by the path

Text files TXT Useful functions in the os.path module exists(path) isfile(path) isdir(path) dirname(path) getsize(path) As usual, more details on the BOOK!

Text files We already talked about characters encoding ASCII and UTF-8 getfilesystemencoding() returns the preferred encoding system used by your system TXT from sys import getfilesystemencoding print(getfilesystemencoding())

Text files TXT We already talked about characters encoding ASCII and UTF-8 getfilesystemencoding() returns the preferred encoding system used by your system You can specify the encoding of a file you open in the open() call h = open( pippo.txt, encoding= ascii )

Text files TXT We already talked about characters encoding ASCII and UTF-8 getfilesystemencoding() returns the preferred encoding system used by your system You can specify the encoding of a file you open in the open() call Opening a file with the wrong encoding might rise an exception h = open( pippo.txt, encoding= ascii )

Exercises Exercise 15.1 in the reference book All exercises in Chapter 16 of the reference book $./hw

Introduction to python 14 Exceptions Rossano Venturini rossano.venturini@unipi.it

Errors Sometimes sh.errors happens! At writing time At runtime if y == 0 printf( 0 ) syntax error if y == 0: printf(5/y) exception

In [1]: 1/0 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-1-05c9758a9c21> in <module>() ----> 1 1/0 ZeroDivisionError: integer division or modulo by zero In [2]: d = {} In [3]: print d[10] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-3-2a1aa1081c87> in <module>() ----> 1 print d[10] KeyError: 10 In [4]: l = [1,2,3] In [5]: print l[42] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-5-cac02ccb7a63> in <module>() ----> 1 print l[42] IndexError: list index out of range

Exceptions Exceptions can be captured

Exceptions Exceptions can be captured

Exceptions Exceptions can be captured try: # block except: # exception handling handling executed if exception raised in block

Exceptions Exceptions can be captured num = getinteger( Give me a number: ) try: print (3/num) except: print( Division by zero! ) print( end )

Exceptions You can address specific exceptions try: print (3/int(input( Give me a number: ))) except ZeroDivisionError: print( Division by zero! ) except ValueError: print( Not an integer! ) except: print( Something else went wrong! )

Exceptions else clause try: num = 3/int(input( Give me a number: )) except ZeroDivisionError: print( Division by zero! ) except ValueError: else: print( Not an integer! ) print(num) Executes only if no exception at all occurs

Exceptions finally clause Executed regardless of how the try clause is exited try: h = open( pippo.txt ) print (h.read()) finally: h.close() Makes sure the file is always closed

Exceptions extra info except. as name clause try: num = int(input( Give me a number: )) except ValueError as ex: print(ex.args) ValueError gets a tuple with only one value (a string) Other errors gets more values

Other examples Empty dictionary. d = {} for i in range(5): x = input() try: d[x] += 1 except: d[x] = 1 print (d)

Other examples Empty dictionary. d = {} for i in range(5): x = input() try: d[x] += 1 except (Exception, TypeError, KeyError) as e: print (type(e), :, e) d[x] = 1 print (d)

Common exceptions ZeroDivisionError y/0 IndexError List or tuple accessed beyond bounds FileNotFoundError Accessing a file that does not exists ValueError Error during a type cast operation.

File handling exceptions IOError the first element of args contains a number that is quite informative to understand exactly what went wrong Use the errno module to have an easier interpretation of these numbers errno.enoent No such file or dir errno.eaccess Permission denied errno.enospc. No more space left on the device

Raising exceptions You are allowed to raise exceptions yourself!

Raising exceptions You are allowed to raise exceptions yourself! When you write a module, and an error occurs, it is not nice to just print a message and exit Just le the caller to handle it!

Raising exceptions You are allowed to raise exceptions yourself! When you write a module, and an error occurs, it is not nice to just print a message and exit Just le the caller to handle it!

Raising exceptions You are allowed to raise exceptions yourself! def getintegermax100(string): s = int(input(string)) if (s > 100): raise ValueError( Too big!, s) return s You can pass here a tuple, that can be accessed as seen before (args)

Raising exceptions raise can also be used with try.except try: num = 3/int(input( Give me a number: )) except ZeroDivisionError: raise except ValueError: else: print( Not an integer! ) print(num) If you are in the main, there are no other levels in the program, so it simply crashes

Exercises Exercise 17.1 in the reference book $./hw