Topic: File Input/Output (I/O)

Slides:



Advertisements
Similar presentations
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
Advertisements

Computer Science 111 Fundamentals of Programming I Files.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 11: 1 CMT1000: Introduction to Programming Ed Currie Lecture 10: File Input.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 0008 Day 2 1. Today Hardware and Software How computers store data How a program works Operators, types, input Print function Running the debugger.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 17 Reading and Writing Files 5/10/09 Python Mini-Course: Lesson 17 1.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
Topics Introduction Hardware and Software How Computers Store Data
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Lecture 16 – Open, read, write and close files.  At the end of this lecture, students should be able to:  understand file structure  open and close.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 1 Introduction to Computers and Programming.
File I/O 11_file_processing.ppt
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
5 1 Data Files CGI/Perl Programming By Diane Zak.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Files Tutor: You will need ….
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])
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Topic: Binary Encoding – Part 2
Chapter 14: Sequential Access Files
Development Environment
COMP Streams and File I/O
Fundamentals of Python: First Programs
Whatcha doin'? Aims: To start using Python. To understand loops.
Topic: Python’s building blocks -> Variables, Values, and Types
Lesson 08: Files Class Participation: Class Chat: Attendance Code 
Topics Introduction Hardware and Software How Computers Store Data
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.
Topic: Python’s building blocks -> Variables, Values, and Types
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Python’s input and output
Exceptions and files Taken from notes by Dr. Neil Moore
Files and Streams Lect3 CT1411.
Ruth Anderson UW CSE 160 Spring 2018
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Basic File I/O and Stream Objects
File IO and Strings CIS 40 – Introduction to Programming in Python
Lesson 08: Files Topic: Introduction to Programming, Zybook Ch 7, P4E Ch 7. Slides on website.
Fundamentals of Programming I Files
File I/O File input/output Iterate through a file using for
Learning to Program in Python
Exceptions and files Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
Topics Introduction Hardware and Software How Computers Store Data
CS 1111 Introduction to Programming Fall 2018
Introduction to Python: Day Three
Lesson 08: Files Class Chat: Attendance: Participation
Files Handling In today’s lesson we will look at:
CISC101 Reminders All assignments are now posted.
15-110: Principles of Computing
Topics Introduction to File Input and Output
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Bryan Burlingame 17 April 2019
CSE 231 Lab 5.
Topics Introduction to File Input and Output
Programming Techniques :: File Handling
Introduction to Computer Science
Presentation transcript:

Topic: File Input/Output (I/O) CMPT 120 Topic: File Input/Output (I/O)

Last Lecture List of lists

Learning outcomes At the end of this course, a student is expected to: Create Python programs that read and write text files (file I/O)

Today’s Menu Another way to get data into our programs (aside from using input( )) and to output data from our program (aside from using print( ))

External storage When we shut down an application (e.g.: Python IDLE, Word or Excel) and/or turn off our computer, often we do not want our information (code, data) to disappear We want our information to persist until the next time we use We achieve persistence by saving our information to files on external storage like hard disk, flash memory, etc…

Files All files contain sequence of 0’s and 1’s (just like computer memory does) However … Binary Files The sequence of 0’s and 1’s represents either microprocessor instructions, colours, etc… To view the content of a binary file, one needs to use the appropriate application (based on the context of the file) Example: a jpg image file (file containing mostly sequence of 0’s and 1’s representing pixel colours) can be rendered (i.e., displayed) using applications such as paint (on Windows platform) or most web browsers

Files Text Files The sequence of 0’s and 1’s represents human-readable characters, i.e., UNICODE/ASCII characters To view the content of a text file, one needs to use the appropriate application such as a text editor Example: In CMPT 120, we shall open/read text files

Open a file in a Python program To use a file in our Python program, we must first open it in the appropriate mode: <fileObject> = open(filename, <mode>) Syntax: Optional string describing the way in which the file will be used Where does the value of the variable filename come from? We can either ask the user to enter a filename (string) using input(), prior to the call to open( ) OR We can assign a filename (string) to this variable at the top of our program, prior to the call to open( )

A word about the file named filename Python interpreter will look for a file with the filename in the current directory What is the current directory? The directory that contains the Python program we are currently running If filename is stored in another directory, we must add the proper path to it: <path/filename> This path can be part of the value assigned to the variable filename filename = path + filename

Absolute vs. relative path Directory structure:

A word about <mode> A mode describes the way in which a file is to be used Python considers the following modes: Read Write Append Read and write

Open a file for reading To read from a file, we need to first open it in read mode with 'r': fileRead = open(<filename>, 'r') OR fileRead = open(<filename>) fileRead is a file object If the file does not exists in the current directory -> Python interpreter produces and prints an error FileNotFoundError: [Errno 2] No such file or directory: 'fileDoesNotExist.txt' Syntax:

Code Example # Either ask user for a filename (and path) # or set your filename variable once at # the top of your program <- Why? inputFile = "bunch_of_words.txt" ... # Opening a file for reading fileR = open(inputFile , 'r') # or fileR = open(inputFile )

Open a file for writing Syntax: To write to a file, we need to first open it in write mode with 'w': fileWrite = open(<filename>, 'w') fileWrite is a file object, i.e., a variable of type class If the file already exists in the directory -> its content is erased, ready to receive new data If the file does not exists in the directory -> it is created Syntax:

Code Example ... outputFile = "newFile.txt" # Opening a file for writing fileW = open(outputFile, 'w')

Open a file for appending To append to a file, we need to first open it in append mode with 'a': fileAppend = open(<filename>, 'a') fileAppend is a file object, i.e., a variable of type class If the file already exists in the directory -> new data will be automatically added to the end of the file, leaving the current content unaffected If the file does not exists in the directory -> it is created Syntax:

Code Example ... outputFile = "newFile.txt" # Opening a file for appending fileA = open(outputFile, 'a')

Open a file for reading and writing To read from and to write to a file, we need to first open it in read and write mode with 'r+': fileReadWrite = open(<filename>, 'r+') fileReadWrite is a file object, i.e., a variable of type class Syntax:

Code Example ... gameFile = "gameSaved.txt" # Opening a file for reading and writing fileRW = open(gameFile, 'r+')

Reading from a file File object provides methods for reading: To read a line from a file into a string: readline( ) reads characters from the file until it reaches a newline character and returns the result as a string The file object keeps track of where it is in the file, so if we call readline( ) again, we get the next line

Code Example # File_IO_Demo_Read_File.py inputFile = 'bunch_of_words.txt' # Opening a file for reading fileR = open(inputFile, 'r') # Read its first line -> a string firstLine = fileR.readline() print("\nfirst line: " , firstLine) print("type(firstLine) is {}.".format(type(firstLine))) # Read its second line # File object keeps track of where it currently is in the file secondLine = fileR.readline() print("\nsecond line: " , secondLine) # Close the file fileR.close( )

Reading from a file (cont’d) Efficient way to read the content of a file using a loop for line in fileR: # strip whitespaces and newline character strippedLine = line.strip # process strippedLine To read all lines from a file into a list: myList = list(fileR) fileR.readlines()

Code Example ... # Opening a file for reading fileR = open(inputFile, 'r') # Read all lines into list myList1 = list(fileR) print("\nfirst list: ", myList1) # Close the file fileR.close( ) myList2 = fileR.readlines( ) print("\nsecond list: ", myList2)

Writing to a file File object provides methods for writing: numOfChars = fileWrite.write(aString) writes the contents of aString to the file, returning the number of characters written To write something other than a string, it needs to be converted to a string first using str( ) String formatting (e.g.: %d) .format() method of string

Code Example See File_IO_Demo_Write_to_File.py and File_IO_Demo_Read_File.py on our course web site

Closing a file Files must be closed <fileobject>.close( ) Why? To finalize the file To free up any system resources taken up by the open file After calling close( ), we cannot use the file object anymore (in our Python program) Syntax:

Dealing with errors We saw that if the file does not exists -> Python interpreter produces and prints an error FileNotFoundError: [Errno 2] No such file or directory: 'fileDoesNotExist.txt' We can write guardian code against this and other errors called “exceptions” -> “exceptions” to the normal flow of execution

Catching exceptions Using the try statement (often called “try block”) fileDoesNotExist = "fileDoesNotExist.txt" try: fin = open(fileDoesNotExist) for line in fin: print(line) # and other processing fin.close() except: print('\n%s not found' %fileDoesNotExist)

Appending to a non-existing file? fileToAppendToDoesNotExist = "fileToAppendToDoesNotExist.txt" # What happen when I append to a non-existing file? fout = open(fileToAppendToDoesNotExist, 'a') fout.write("Banana") fout.close( )

Code Example See File_IO_Demo_Error_and_Exception.py on our course web site to see a code example of what one can do when a file does not exist

Exercise 9.1 (textbook page 84) Exercise 9.1 Write a program that reads words.txt and prints only the words with more than 20 characters (not counting whitespace).

Summary Another way to get data into our programs (aside from using input( )) and to output data from our program (aside from using print( )) Files binary and text files Absolute and relative paths Open, read, write, append and close Error: exceptions

Next Lecture Binary Encoding