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.

Slides:



Advertisements
Similar presentations
I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
Advertisements

 Computer Science 1MD3 Introduction to Programming Winter 2014.
CompSci 101 Introduction to Computer Science February 3, 2015 Prof. Rodger Lecture given by Elizabeth Dowd.
Adapted from John Zelle’s Book Slides
Python Programming: An Introduction to Computer Science
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.
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.
True BASIC Ch. 6 Practice Questions. What is the output? PRINT X LET X = -1 PRINT X FOR X = 4 TO 5 STEP 2 PRINT X NEXT X PRINT X END.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 11: 1 CMT1000: Introduction to Programming Ed Currie Lecture 10: File Input.
James Tam Arrays / Lists In this section of notes you will be introduced to new type of variable that consists of other types.
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.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
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 Lists In this section of notes you will be introduced to new type of variable that consists of other types.
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.
Exceptions COMPSCI 105 S Principles of Computer Science.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
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.
General Programming Introduction to Computing Science and Programming I.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
Introduction. 2COMPSCI Computer Science Fundamentals.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
File I/O ifstreams and ofstreams Sections 11.1 &
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
C++ Classes and Data Structures Jeffrey S. Childs
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)
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
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])
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
Lecture 4 Python Basics Part 3.
1 CSC103: Introduction to Computer and Programming Lecture No 27.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Python File Handling. Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations.
Introduction To Files In Python
Introduction to Computing Science and Programming I
Topic: File Input/Output (I/O)
Fundamentals of Python: First Programs
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.
Computer Programming Fundamentals
Lesson 4 - Challenges.
Engineering Innovation Center
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Using files Taken from notes by Dr. Neil Moore
Introduction To Files In Python
Introduction To Files In Python
Introduction to Python: Day Three
Reading and Writing Files
Topics Introduction to File Input and Output
Chopin’s Nocturne.
Topics Introduction to File Input and Output
Introduction to Computer Science
Presentation transcript:

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 Why Bother With Files? Many reasons: -Too much information to input all at once -The information must be persistent (RAM is volatile) -Data entry of information is easier via a specialized program (text editor, word processor, spreadsheet, database) rather than through the computer program that you write. -Etc.

James Tam What You Need In Order To Read Information From A File 1.Open the file and associate the file with a file variable 2.A command to read the information 3.A command to close the file

James Tam 1.Opening Files Prepares the file for reading: A.Links the file variable with the physical file (references to the file variable are references to the physical file). B.Positions the file pointer at the start of the file. C.The file may be ‘locked’ Format: 1 = open (, “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 Assumes that the file is in the same directory/folder as the Python program.

James Tam B.Positioning The File Pointer A B C B : letters.txt

James Tam 2.Reading Information From Files Typically reading is done within the body of a loop Format: for in : Example: for line in inputFile: print(line)

James Tam Closing The File Although a file is automatically closed when your program ends it is still a good idea to explicitly close your file as soon as the program is done with it. Format:. () Example: inputFile.close()

James Tam Reading From Files: Putting It All Together Name of the online example: grades1.py 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)

James Tam What You Need To Write Information To A File 1.Open the file and associate the file with a file variable (file is “locked” for writing). 2.A command to write the information 3.(A command to close the file)

James Tam 1.Opening The File Format: = open (, “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")

James Tam 3.Writing To A File Format: outputFile.write (temp) Example: # Assume that temp contains a string of characters. outputFile.write (temp)

James Tam Writing To A File: Putting It All Together Name of the online example: grades2.py 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.")

James Tam Writing To A File: Putting It All Together (2) gpa = 0 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

James Tam Writing To A File: Putting It All Together (3) # (Body of for-loop continued) temp = str (gpa) temp = temp + '\n' print (line[0], '\t', gpa) outputFile.write (temp) # Finished writing to file, provide feedback to user and close file. inputFile.close () outputFile.close () print ("Completed reading of file", inputFileName) print ("Completed writing to file", outputFileName)

James Tam Another Example Reading From A File Into A String: Access Individual Characters Name of the online example: file_list.py inputFile = open ("input.txt", "r") i = 1 for line in inputFile: print("Line %d vowels:" %i) for ch in line: if (ch in ('A','a','E','e','I','i','O','o','U','u')): sys.stdout.write(ch) i = i + 1 print() print ("Completed reading of file input.txt") inputFile.close()

James Tam Building An Arbitrary Sized List By Reading From File Name of the online example: file_list2.py inputFile = open ("input2.txt", "r") myList = [] for line in inputFile: myList.append(line) inputFile.close()

James Tam Building An Arbitrary Sized List By Reading From File (2) row = 0 for line in myList: if (row < 10): temp = str(row) + line sys.stdout.write(temp) else: temp = (row - 10) + ord('A') ch = chr(temp) temp = ch + line sys.stdout.write(temp) row = row + 1

James Tam __str__() A special method that is automatically called when an object is passed into the ‘ print ’ function. Because print takes a string or strings as parameters the __str__() method must return a string ( print calls __str__ ) -Normally the string returned contains information about the attributes. Format: def __str__(self, ): ::: return Example 1 : class Foo: x = 12 def __str__(self): return(str(self.x)) 1 Full example to follow.

James Tam Reading File Information Into A List Of Objects Name of the online example: client_tracker.py NET_WORTH_CUTOFF = class Client: def __init__(self,name,worth): self.name = name self.worth = worth def __str__(self): temp = "Client name: " + self.name temp = temp + "\n" temp = temp + "Net worth $" + str(self.worth) return temp

James Tam Reading File Information Into A List Of Objects (2) class SpecialClient: WORTH_TO_HAPPINESS_RATIO = def __init__(self,name,worth): self.name = name self.worth = worth # Amount of money we will spend on the client to keep his/her # business (i.e., we will spend more on richer clients). self.expenseAccount = int(self.worth * \ self.WORTH_TO_HAPPINESS_RATIO) def __str__(self): temp = "Client name: " + self.name temp = temp + "\n" temp = temp + "Net worth $" + str(self.worth) temp = temp + "\n" temp = temp + "Client budget $" + str(self.expenseAccount) return temp

James Tam Reading File Information Into A List Of Objects (3) def readClientInformationFromFile(): clients = [] inputFile = open("clients.txt", "r") for line in inputFile: name,worth = line.split('$') worth = int(worth) if (worth >= NET_WORTH_CUTOFF): aClient = SpecialClient(name,worth) else: aClient = Client(name,worth) clients.append(aClient) return clients

James Tam Reading File Information Into A List Of Objects (4) def display(clients): MAX = len(clients) print() print("CLIENT LIST") print(" ") for i in range (0,MAX,1): print("Client #%d" %(i+1)) print(clients[i]) print("~~~~~~~~~~~~~~~~~~~~~~~~~~") def main(): clients = readClientInformationFromFile() display(clients) main()

James Tam Error Handling With Exceptions Exceptions are used to deal with extraordinary errors. Typically these are fatal runtime errors. Example: trying to open an non-existent file

James Tam Exceptions: Example Name of the online example: file_exception.py inputFileOK = False while (inputFileOK == False): try: inputFileName = input ("Enter name of input file: ") inputFile = open (inputFileName, "r") except IOError: print ("File", inputFileName, "could not be opened") else: print ("Opening file", inputFileName, " for reading.") inputFileOK = True for line in inputFile: sys.stdout.write(line) print ("Completed reading of file", inputFileName) inputFile.close() print ("Closed file", inputFileName)

James Tam Exceptions: Example (2) # Body of the while loop (continued) finally: if (inputFileOK == True): print ("Successfully read information from file", inputFileName) else: print ("Unsuccessfully attempted to read information from file", inputFileName)

James Tam 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 How to build an arbitrary sized list by reading the information from a file How exceptions can be used in conjunction with file input