Introduction To Files In Python

Slides:



Advertisements
Similar presentations
Computer Science 111 Fundamentals of Programming I Files.
Advertisements

J. Michael Moore Text Files CSCE 110 From James Tam’s material.
Slide 1 Introduction To Files In Python In this section of notes you will learn how to read from and write to text files.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in your Pascal programs.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
James Tam Introduction To Files In Pascal You will learn how to read from and write to text files in Pascal.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to text files in Pascal.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
11 Chapter 4 LOOPS AND FILES CONT’D. 22 SENTINEL-CONTROLLED LOOPS Suppose we did not know the number of grades that were to be entered. Maybe, a single.
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.
General Programming Introduction to Computing Science and Programming I.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
File I/O ifstreams and ofstreams Sections 11.1 &
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
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.
Python File Handling. Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations.
The Little man computer
Introduction to Computing Science and Programming I
Agenda Introduction Computer Programs Python Variables Assignment
Topic: File Input/Output (I/O)
Fundamentals of Python: First Programs
IGCSE 4 Cambridge Data types and arrays Computer Science Section 2
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.
Lesson 04: Conditionals Topic: Introduction to Programming, Zybook Ch 3, P4E Ch 3. Slides on website.
Topics Introduction to Repetition Structures
Python’s input and output
Design & Technology Grade 7 Python
Handling errors try except
Algorithm and Ambiguity
Engineering Innovation Center
Exceptions and files Taken from notes by Dr. Neil Moore
Imperative Programming
Selection CIS 40 – Introduction to Programming in Python
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Number and String Operations
More Loops.
Introduction To Files In Python
Fundamentals of Programming I Files
Exceptions and files Taken from notes by Dr. Neil Moore
Algorithm Discovery and Design
Fundamentals of Data Structures
I210 review.
ERRORS AND EXCEPTIONS Errors:
The ‘while’ loop ‘round and ‘round we go.
If selection construct
Introduction To Files In Python
Text / Serial / Sequential Files
Reading and Writing Files
CSC115 Introduction to Computer Programming
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
User Input Keyboard input.
Loops.
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.
CSE 231 Lab 5.
Topics Introduction to File Input and Output
Introduction to C Programming
Imperative Programming
Flow Control I Branching and Looping.
Dealing with Runtime Errors
Presentation transcript:

Introduction To Files In Python In this section of notes you will learn how to read from and write to text files Introduction to files in Pascal 1

What You Need In Order To Read Information From A File Open the file and associate the file with a file variable. A command to read the information. A command to close the file. Introduction to files in Pascal 2

Opening Files Prepares the file for reading: Format:1 Example: Links the file variable with the physical file (references to the file variable are references to the physical file). Positions the file pointer at the start of the file. Format:1 <file variable> = open(<file name>, "r") Example: (Constant file name) inputFile = open("data.txt", "r") OR (Variable file name: entered by user at runtime) filename = input("Enter name of input file: ") inputFile = open(filename, "r") 1 Examples assume that the file is in the same directory/folder as the Python program. Introduction to files in Pascal 3

Positioning The File Pointer letters.txt A B C : Introduction to files in Pascal 4

Reading Information From Files Typically reading is done within the body of a loop Each execution of the loop will read a line from file into a string Format: for <variable to store a string> in <name of file variable>: <Do something with the string read from file> Example: for line in inputFile: print(line) # Echo file contents back onscreen Introduction to files in Pascal 5

Closing The File Although a file is automatically closed when your program ends it is still a good style to explicitly close your file as soon as the program is done with it. What if the program encounters a runtime error and crashes before it reaches the end? The input file may remain ‘locked’ an inaccessible state because it’s still open. Format: <name of file variable>.<close>() Example: inputFile.close()

Reading From Files: Putting It All Together Name of the online example: grades1.py Input files: letters.txt or gpa.txt inputFileName = input("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") for line in inputFile: sys.stdout.write(line) inputFile.close() print("Completed reading of file", inputFileName) Introduction to files in Pascal 7

What You Need To Write Information To A File Open the file and associate the file with a file variable (file is “locked” for writing). A command to write the information. A command to close the file. Introduction to files in Pascal 8

Opening The File Format1: Example: (Constant file name) <name of file variable> = open(<file name>, "w") Example: (Constant file name) outputFile = open("gpa.txt", "w") (Variable file name: entered by user at runtime) outputFileName = input("Enter the name of the output file to record the GPA's to: ") outputFile = open(outputFileName, "w") 1 Typically the file is created in the same directory/folder as the Python program. Introduction to files in Pascal 9

Writing To A File You can use the ‘write()’ function in conjunction with a file variable. Note however that this function will ONLY take a string parameter (everything else must be converted to this type first). Format: outputFile.write(temp) Example: # Assume that temp contains a string of characters. outputFile.write (temp) Introduction to files in Pascal 10

Writing To A File: Putting It All Together Name of the online example: grades2.py Input file: “letters.txt” (sample output file name: gpa.txt) inputFileName = input("Enter the name of input file to read the grades from: ") outputFileName = input("Enter the name of the output file to record the GPA's to: ") inputFile = open(inputFileName, "r") outputFile = open(outputFileName, "w") print("Opening file", inputFileName, " for reading.") print("Opening file", outputFileName, " for writing.") gpa = 0 Introduction to files in Pascal 11

Writing To A File: Putting It All Together (2) for line in inputFile: if (line[0] == "A"): gpa = 4 elif (line[0] == "B"): gpa = 3 elif (line[0] == "C"): gpa = 2 elif (line[0] == "D"): gpa = 1 elif (line[0] == "F"): gpa = 0 else: gpa = -1 temp = str (gpa) temp = temp + '\n' print (line[0], '\t', gpa) outputFile.write (temp)

Writing To A File: Putting It All Together (3) inputFile.close () outputFile.close () print ("Completed reading of file", inputFileName) print ("Completed writing to file", outputFileName)

Reading From Files: Commonly Used Algorithm (If There Is Time) Pseudo-code: Read a line from a file as a string While (string is not empty) process the line e.g. display onscreen, use data in some calculations etc. Read another line from the file

File Input: Alternate Implementation Name of the online example: grades3.py inputFileName = input ("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") line = inputFile.readline() while (line != ""): print(line, end="") inputFile.close() print("Completed reading of file", inputFileName)

Data Processing: Files Files can be used to store complex data given that there exists a predefined format. Format of the example input file: ‘employees.txt’ <Last name><SP><First Name>,<Occupation>,<Income>

Example Program: data_processing.py # EMPLOYEES.TXT Adama Lee,CAG,30000 Morris Heather,Heroine,0 Lee Bruce,JKD master,100000 inputFile = open ("employees.txt", "r") print ("Reading from file input.txt") for line in inputFile: name,job,income = line.split(',') # Divided by the comma last,first = name.split() income = int(income) income = income + (income * BONUS) print("Name: %s, %s\t\t\tJob: %s\t\tIncome $%.2f" %(first,last,job,income)) print ("Completed reading of file input.txt") inputFile.close()

Error Handling With Exceptions Exceptions are used to deal with extraordinary errors (‘exceptional ones’). Typically these are fatal runtime errors (“crashes” program) Example: trying to open a non-existent file Basic structure of handling exceptions Try: Attempt something where exception error may happen Except: React to the error Else: # Not always needed What to do if no error is encountered Finally: # Not always needed Actions that must always be performed

Exceptions: File Example Name of the online example: file_exception.py Input file name: Most of the previous input files can be used e.g. “input1.txt” inputFileOK = False while (inputFileOK == False): try: inputFileName = input("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file" + inputFileName, " for reading.") inputFileOK = True for line in inputFile: sys.stdout.write(line) print("Completed reading of file", inputFileName)

Exceptions: File Example (2) # Still inside the body of the while loop (continued) inputFile.close() print("Closed file", inputFileName) # End of try-body except IOError: print("Error: File", inputFileName, "could not be opened") else: print("Successfully read information from file", inputFileName) finally: print("Finished file input and output\n")

Exception Handling: Keyboard Input Name of the online example: exception_validation.py inputOK = False while (inputOK == False): try: num = input("Enter a number: ") num = float(num) except ValueError: # Can’t convert to a number print("Non-numeric type entered '%s'" %num) else: # All characters are part of a number inputOK = True num = num * 2 print(num)

You Should Now Know How to open a file for reading How to open a file a file for writing The details of how information is read from and written to a file How to close a file and why it is good practice to do this explicitly How to read from a file of arbitrary size Data storage and processing using files and string functions How exceptions can be used in conjunction with file input and with invalid keyboard/console input Introduction to files in Pascal 22