Copyright (c) 2017 by Dr. E. Horvath

Slides:



Advertisements
Similar presentations
Introduction to Computing Science and Programming I
Advertisements

Loops (Part 1) Computer Science Erwin High School Fall 2014.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
CIS199 Test Review 2 REACH.
Control Structures I Chapter 3
C++ Exceptions.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Topic: File Input/Output (I/O)
User-Written Functions
Repetition Structures
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.
Control Structures II Chapter 3
What to do when a test fails
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Copyright (c) 2017 by Dr. E. Horvath
Computer Programming I
EET 2259 Unit 5 Loops Read Bishop, Sections 5.1 and 5.2.
CS 115 Lecture 8 Structured Programming; for loops
Exception Handling.
Exceptions and files Taken from notes by Dr. Neil Moore
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Control Statement Examples
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Exception Handling.
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
EET 2259 Unit 5 Loops Read Bishop, Sections 5.1 and 5.2.
Exceptions and files Taken from notes by Dr. Neil Moore
Iteration: Beyond the Basic PERFORM
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Do While (condition is true) … Loop
Repetition Structures
ERRORS AND EXCEPTIONS Errors:
File Handling.
3. Decision Structures Rocky K. C. Chang 19 September 2018
Input from the Console This video shows how to do CONSOLE input.
Exception Handling.
Python programming exercise
CSC115 Introduction to Computer Programming
Please use speaker notes for additional information!
CISC101 Reminders All assignments are now posted.
For loops Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Introduction to Programming
Another Example Problem
Exception Handling Contents
Copyright (c) 2017 by Dr. E. Horvath
Copyright (c) 2017 by Dr. E. Horvath
Text Copyright (c) 2017 by Dr. E. Horvath
Copyright (c) 2017 by Dr. E. Horvath
CSE 231 Lab 5.
Python Conditionals: The if statement
Topics Introduction to File Input and Output
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
EET 2259 Unit 7 Case Structures; Sequence Structures
EET 2259 Unit 5 Loops Read Bishop, Sections 5.1 and 5.2.
CMSC 202 Exceptions 2nd Lecture.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Switch Case Structures
Data Types and Expressions
Presentation transcript:

Copyright (c) 2017 by Dr. E. Horvath FILES Files are accessed using the following statement: my_file = open(my_file_string, permission_string) The argument, my_file_string, contains the name of the file to be accessed; it will often be of the form “the_data_1.txt”. The argument, permission_string, informs the interpreter whether the file is to be read to or written to or both. Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath File Permissions permission_string = “r” read-only permission_string = “w” write-only permission_string = “a” data is appended at the end of the file permission_string = “r+” read and write Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Creating a New File A new file is created by using the open statement with the permission_string set to “w”. euro_city_file = open(“euro_city.txt”,”w”) print(“Grommer's European Vacation Planner”) while True: user_response = input(“Enter a European city”) if user_response == “exit”: break else: print(user_response, file = euro_city_file) euro_city_file.close() Copyright (c) 2017 by Dr. E. Horvath

Creating a New File with Exception Handling If the user failed to enter exit when running the code given on the previous slide and pressed ctrl-c instead, then the data would not have been written to the file. It's always good programming practice to enclose the code in a try-except-finally block, so that the data that is entered will actually be written to the file and so the file will be closed. By handling the KeyboardInterrupt, you enable the rest of the code to be executed. In the except KeyboardInterrupt suite, we simply have a pass statement because, in this example, we just want the code to finish executing. Code in the finally suite is executed regardless of whether an exception is thrown or not. Since a file should always be closed when the code is finished, the close statement is placed here. Copyright (c) 2017 by Dr. E. Horvath

Creating a New File with Exception Handling try: euro_city_file = open(“euro_city.txt”,”w”) print(“Grommer's European Vacation Planner”) while True: user_response = input(“Enter a European city”) if user_response == “exit”: break else: print(user_response, file = euro_city_file) except KeyboardInterrupt: pass finally: euro_city_file.close() Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Reading Files To read from a file, you first need to open the file with the permission string, “r”. You can iterate through the lines of the file using a for loop. travel_file = open(“euro_city.txt”,”r”) for city_str in euro_city_file: city_str = city_line_str.strip() #This strips the extra line print(city_str) travel_file.close() Copyright (c) 2017 by Dr. E. Horvath

Reading Files with Exception Handling If the code attempts to read from a file that does not exist, then a FileNotFoundError will be thrown. The following code displays one way this error could be handled. try: user_reponse = input(“Please enter the travel planner file: “) travel_file = open(user_response,”r”) for travel_str in travel_file: travel_str = travel_str.strip() print(travel_str) travel_file.close() except FileNotFoundError: print(“File not found”) Copyright (c) 2017 by Dr. E. Horvath

Reading Files with Exception Handling: An Alternative Method The code keeps prompting the user for a filename until the user enters a valid one. Notice that the try-except suite is inside of the while loop. while True: try: user_reponse = input(“Please enter the travel file“) travel_file = open(user_response,”r”) for travel_str in travel_file: travel_str = travel_str.strip() print(travel_str) travel_file.close() break except FileNotFoundError: print(“File not found. Try again”) Copyright (c) 2017 by Dr. E. Horvath

Reading Files with Even Better Exception Handling try: while True: user_reponse = input(“Please enter the travel file“) travel_file = open(user_response,”r”) for travel_str in travel_file: travel_str = travel_str.strip() print(travel_str) travel_file.close() break except FileNotFoundError: print(“File not found. Try again”) except KeyboardInterrupt: print(“I guess you are staying home!”) Copyright (c) 2017 by Dr. E. Horvath

Appending Data to Files To append data to a file, you first need to open the file with the permission string, “a”. If the file already exists then any additional data will be added to the end of the file. If the file doesn't yet exist, a new file will be created. Regarding appending data, because the FileNotFoundError will not be thrown do not add code to catch this exception. Copyright (c) 2017 by Dr. E. Horvath

Appending Data to Files The following code prompts the user for a file. If the file exists, then additional data will be appended to the file. If it doesn't exist then a new file will be created. Try this code out both ways. try: user_response = input(“Please enter a travel file: “) travel_file = open(user_response,”a”) while True: new_city_str = input(“Enter a city: “) if new_city_str == “exit”: break else: print(new_city_str,file=travel_file) except KeyboardInterrupt: pass finally: travel_file.close() Copyright (c) 2017 by Dr. E. Horvath

Reading/Writing Data to Files On the previous slides, you opened files with read only and write only permissions. You can also open files with read/write permission. Let's consider the “r+” permission. The code on the following slide prompts the user for a file. This code should be enclosed in a try-except-finally block in case the file the code attempts to open does not exist. After the file is opened, the contents are printed to the shell. Next the user is prompted for new cities which are written to the end of the file. Copyright (c) 2017 by Dr. E. Horvath

Reading/Writing Data to Files Example try: user_response = input("Please enter a travel file: ") travel_file = open(user_response,"r+") for city_str in travel_file: city_str = city_str.strip() print(city_str) while True: new_city_str = input("Enter a city: ") if new_city_str == "exit": break else: print(new_city_str,file=travel_file) except KeyboardInterrupt: pass travel_file.close() except FileNotFoundError: print("File Not Found") Copyright (c) 2017 by Dr. E. Horvath

Files and Lists Example You will usually want to do more with the data that's stored in a file than simply print it out to the shell. The following snippet of code reads data from a file and stores it in a list: euro_city_list = [ ] try: travel_file = open(“euro_city.txt",”r") for city_str in travel_file: city_str = city_str.strip() euro_city_list.append(city_str) travel_file.close() except FileNotFoundError: print("File Not Found") Copyright (c) 2017 by Dr. E. Horvath

File of Numbers Example Since data is stored as strings in files, you would need to cast the strings into floats or integers in order to perform mathematical operations on the data. On this slide is the code that uses the SenseHat to record temperature data and write that data to a file. On the following slide, the temperature data is read into memory and some mathematical analysis is performed on the data. from sense_hat import SenseHat from time import sleep sense = SenseHat() temperature_file = open("temp1.txt","w") for count in range(0,10): temp = sense.get_temperature() print(temp,file=temperature_file) print(temp) sleep(1) temperature_file.close() sense.clear() Copyright (c) 2017 by Dr. E. Horvath

File of Numbers Example Cont'd try: temperature_file = open("temp1.txt","r") temp_c_list = [ ] temp_f_list = [ ] for temp_str in temperature_file: temp_c = float(temp_str.strip()) temp_c_list.append(temp_c) temp_f = 9.0/5.0 * temp_c + 32.0 temp_f_list.append(temp_f) temperature_file.close() temp_c_avg = sum(temp_c_list)/len(temp_c_list) temp_f_avg = 9.0/5.0*temp_c_avg + 32.0 print("Average temperature is ",str(temp_c_avg),"C") print("Average temperature is ",str(temp_f_avg),"F") speed_of_sound = 331.5 + 0.6*temp_c_avg print("Speed of sound is ", str(speed_of_sound) ,"m/s") except FileNotFoundError: print("File not found") Copyright (c) 2017 by Dr. E. Horvath

File of Numbers Example Explanation By placing the analysis code inside of the try-except block, it is guaranteed that this code will be reached only if the temperature data file was opened successfully. Two lists are created, one for the temperature in Celsius and one for the temperature in Fahrenheit. Each Celsius temperature is read in from the file, cast to floating point number, and appended to temp_c_list. The strip method is used to remove new lines and carriage returns. The temperature data is converted into Fahrenheit and stored in temp_f_list. The data file is then closed since the code is finished with it. Next the average Celsius temperature and average Fahrenheit temperature are calculated as well as the speed of sound based on the average Celsius temperature. Copyright (c) 2017 by Dr. E. Horvath