CSE 231 Lab 5.

Slides:



Advertisements
Similar presentations
Handling Errors Introduction to Computing Science and Programming I.
Advertisements

More on Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
Python File Handling. In all the programs you have made so far when program is closed all the data is lost, but what if you want to keep the data to use.
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.
Course A201: Introduction to Programming 12/9/2010.
Python – reading and writing files. ??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
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,
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
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])
Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim.
1 Essential Computing for Bioinformatics Bienvenido Vélez UPR Mayaguez Lecture 3 High-level Programming with Python Part III: Files and Directories Reference:
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”
File Processing Upsorn Praphamontripong CS 1110
Introduction To Files In Python
Reading Files Chapter 7 Python for Everybody
Topic: File Input/Output (I/O)
Lesson 08: Files Class Participation: Class Chat: Attendance Code 
Example: Vehicles What attributes do objects of Sedan have?
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.
Handling Exceptionally Sticky Problems
File Writing Upsorn Praphamontripong CS 1110
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CSc 120 Introduction to Computer Programing II
Computer Science 111 Fundamentals of Programming I
Python’s input and output
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Exceptions and File Input
Engineering Innovation Center
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Exception Handling.
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.
Introduction To Files In Python
Exceptions and files Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
Fundamentals of Data Structures
I210 review.
Changing one data type into another
More Looping Structures
CS 1111 Introduction to Programming Fall 2018
Introduction To Files In Python
Introduction to Python: Day Three
Using Text Files in Python
Input from the Console This video shows how to do CONSOLE input.
Lesson 08: Files Class Chat: Attendance: Participation
Reading and Writing Files
Advanced Python Concepts: Exceptions
Topics Introduction to File Input and Output
Advanced Python Concepts: Exceptions
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Bryan Burlingame 17 April 2019
Handling Exceptionally Sticky Problems
Python - Files.
General Computer Science for Engineers CISC 106 Lecture 03
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Copyright (c) 2017 by Dr. E. Horvath
More Looping Structures
Topics Introduction to File Input and Output
Copyright (c) 2017 by Dr. E. Horvath
File Handling.
CS 1111 Introduction to Programming Spring 2019
Files A common programming task is to read or write information from/to a file.
Introduction to Computer Science
Presentation transcript:

CSE 231 Lab 5

Files: open file to read/write exceptions Topics to cover Files: open file to read/write exceptions

Open file to read/write file_obj = open(filename_str,"r") file_obj_out = open(filename2_str,"w") What is “r”? What is “w”?

Files in Python – r mode file_name = “input.txt” the_file = open(file_name, “r”) for line in the_file: print(line) the_file.close() #Read one line at a time input.txt First Line Second Line Third Line

Files in Python – r mode Why the extra blank lines? Every line ends with this character: ‘\n’ This indicates the END of a line and all files who have multiple lines have them. Why the extra blank lines? How do we get rid of whitespace???

Files in Python – r mode file_name = “input.txt” the_file = open(file_name, “r”) for line in the_file: # Get rid of only whitespaces at the end of the string line = line.strip() print(line) the_file.close()

print(“Hello World!”, file = file_obj_out) Files in Python – w mode file_name = “input.txt” file_obj_out = open(file_name,"w" ) file_obj_out.write(“Hello World!”) file_name = “input.txt” file_obj_out = open(file_name,"w" ) print(“Hello World!”, file = file_obj_out)

Files in Python – w mode filename2_str = “test.txt” file_obj_out = open(filename2_str,"w") # What is that “w”? print(“Hello World!”, file = file_obj_out) There is nothing in the file!

Open file to read/write filename2_str = “test.txt” file_obj_out = open(filename2_str,"w") print(“Hello World!”, file = file_obj_out) file_obj_out.close() # ALWAYS CLOSE THE FILE!

Is this correct? Files in Python – w mode the_file = open(“test.txt”, “w”) # What is that “w”? for line in the_file: print(line) the_file.close() Is this correct?

File Opening in Python – w mode

What will be printed? Files in Python – w mode input_str="{:>10s} is {:<10d} years old".format("Bill",25) the_file = open(“test.txt”, “w”) print(‘First line’, file = the_file) print(‘Second line’, file = the_file) print(input_str, file = the_file) the_file.close() What will be printed?

Open file modes '' r'' reading only mode. Start at the beginning of the file. ''w'' Writing only mode. Override the file if exists or create text file for writing. ''a'' Open for appending. The file is created if it does not exist. Start at the end of the file. Subsequent writes to the file will always end up at the current end of file ''r+'' Open for reading and writing. Start at the beginning of the file. ''w+'' Open for reading and writing. Override the file if exists or create text file for writing. Starts at the beginning of the file. ''a+'' Open for reading and appending. The file is created if it does not exist. Start at the end of the file. Subsequent writes to the file will always end up at the current end of file

What will happen? File Opening in Python the_file = open(“test_oops.txt”, “r” ) # test_oops.txt file does not exit What will happen?

File Opening in Python – FileNotFoundError Here we have a specific exception that was thrown, FileNotFoundError. We want to be able to catch that mistake and handle it.

What happens if the file doesn’t exist? FileNotFoundError: [Errno 2] No such file or directory: ‘filename’ How to catch that exception: try: file_obj = open(filename_str,"r") except FileNotFoundError: print(“File doesn’t exist!”) You can do it in a loop to keep prompting the user for a valid filename Much safer and our code does not crash 

What happens if the file doesn’t exist? How to catch exceptions: try: filename_str = input() file_obj = open(filename_str,"r") file_obj.close() except : #catch general exceptions print(“File doesn’t exist!”) You can do it in a loop to keep prompting the user for a valid filename Much safer and our code does not crash 

Testing for types Example: Check if the string input is a float. Create your own function is_float(s) to check for floats def is_float(s) try: float(s) # s is a string return True except ValueError : return False You can do it in a loop to keep prompting the user for a valid float