Copyright (c) 2017 by Dr. E. Horvath

Slides:



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

Files in Python The Basics. Why use Files? Very small amounts of data – just hardcode them into the program A few pieces of data – ask the user to input.
Files in Python Caution about readlines vs. read and split.
Files in Python Input techniques. Input from a file The type of data you will get from a file is always string or a list of strings. There are two ways.
Group practice in problem design and problem solving
Lists in Python.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Files Tutor: You will need ….
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Chapter 2 Writing Simple Programs
Microsoft Visual Basic 2005: Reloaded Second Edition
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.
Objectives You should be able to describe: Interactive Keyboard Input
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Copyright (c) 2017 by Dr. E. Horvath
Computer Programming I
Prof: Dr. Shu-Ching Chen TA: Samira Pouyanfar Hector Cen Fall 2017
Scripts & Functions Scripts and functions are contained in .m-files
Data Structures Mohammed Thajeel To the second year students
Exceptions and files Taken from notes by Dr. Neil Moore
Chapter 14: Exception Handling
Little work is accurate
Python Primer 2: Functions and Control Flow
File Handling Programming Guides.
Topics Introduction to File Input and Output
Exception Handling.
Fundamentals of Programming I Files
Exceptions and files Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
1) C program development 2) Selection structure
String Manipulation Chapter 7 Attaway MATLAB 4E.
CISC101 Reminders Quiz 1 grading underway Next Quiz, next week.
Fundamentals of Data Structures
Lists in Python Creating lists.
Input from the Console This video shows how to do CONSOLE input.
Topics Sequences Introduction to Lists List Slicing
Elements of a Python Program
Python programming exercise
Basic String Operations
CISC101 Reminders All assignments are now posted.
CHAPTER 6: Control Flow Tools (for and while loops)
Topics Introduction to File Input and Output
Topics Basic String Operations String Slicing
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Topics Sequences Introduction to Lists List Slicing
Copyright (c) 2017 by Dr. E. Horvath
Topics Basic String Operations String Slicing
Text Copyright (c) 2017 by Dr. E. Horvath
General Computer Science for Engineers CISC 106 Lecture 03
CSE 231 Lab 5.
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.
Introduction to Dictionaries
EECE.2160 ECE Application Programming
Copyright (c) 2017 by Dr. E. Horvath
Class code for pythonroom.com cchsp2cs
Topics Basic String Operations String Slicing
Presentation transcript:

Copyright (c) 2017 by Dr. E. Horvath FILES-Methods to Read In the first set of PowerPoint slides on file access, you learned just one way to read from a file; essentially you used a loop to iterate through the lines in a file. There are three methods that can be used to read from a file: readline, readlines, and read(size_in_bytes). Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath The readline method Use the temp1.txt data file that was created when you ran the code that was included in the first set of PowerPoint slides on files. The following snippet of code uses the readline method to read in one line of code. try: the_temp_file = open("temp1.txt","r") print(the_temp_file.readline().strip()) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

More on the readline method The following snippet of code uses the readline method to read in every line. try: the_temp_file = open("temp1.txt","r") for i in range(0,10): print(the_temp_file.readline().strip()) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

More on the readline method The following snippet of code uses the readline method to read in every line. try: the_temp_file = open("temp1.txt","r") for i in range(0,10): print(the_temp_file.readline().strip()) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

More on the readline method The following snippet of code uses the readline method to read in every line. This code isn't well designed because you would have to know the length of the file in advance in order to hard code the number of iterations. The iterative technique discussed in the previous set of slides accomplishes the same goal and does so neatly. try: the_temp_file = open("temp1.txt","r") for i in range(0,10): print(the_temp_file.readline().strip()) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath The readlines method The readlines method reads in every line of code and stores each line as a separate element in a list. This is a convenient method to use because the reading in and storing of the data is handled in one line of code. try: the_temp_file = open("temp1.txt","r") the_temp_list = the_temp_file.readlines() the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

Reading Files One Byte at a Time The read(size_in_bytes) method allows the programmer to read data in blocks of bytes. The following snippet of code reads in the first twenty characters one at a time: try: the_temp_file = open("temp1.txt","r") for i in range(0,20): print(the_temp_file.read(1)) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

Reading Files One Byte at a Time Cont'd To read in more than one byte at a time, simply change the argument of the read method to that number of bytes: try: the_temp_file = open("temp1.txt","r") for i in range(0,20): print(the_temp_file.read(3)) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

Reading Files One Byte at a Time Cont'd The method read(), without any argument, causes the rest of the file to be read in: try: the_temp_file = open("temp1.txt","r") for i in range(0,20): print(the_temp_file.read(3)) print(the_temp_file.read()) the_temp_file.close() except FileNotFoundError: print("The file wasn't found") Copyright (c) 2017 by Dr. E. Horvath

The write() Method to Write to Files The following code prompts the user to enter a grocery item in an endless. The user breaks out of the loop by pressing ctrl-c, and the code catches the KeyboardInterrupt. grocery_file = open("groceries.txt","w") try: while True: user_response = input("Enter a product: ") grocery_file.write(user_response) except KeyboardInterrupt: pass grocery_file.close() Copyright (c) 2017 by Dr. E. Horvath

The write() method cont'd. The problem with the previous code is that each item the user enters is tacked onto one long string without any line breaks. The following code fixes that problem by adding a plus sign and '\n', which is the symbol for newline: grocery_file = open("groceries.txt","w") try: while True: user_response = input("Enter a product: ") grocery_file.write(user_response + '\n') except KeyboardInterrupt: pass grocery_file.close() Copyright (c) 2017 by Dr. E. Horvath

The writelines() Method A list can be written to a file using one file. The following snippet of code reads data in from the groceries.txt file using the readlines() method, converts each item to upper case, and uses the writelines() method to write the list to a new file, ugroceries.txt. try: grocery_file = open("groceries.txt","r") grocery_list = grocery_file.readlines() for item in range(0,len(grocery_list)): print(grocery_list[item].upper()) ugrocery_file = open("ugroceries.txt","w") ugrocery_file.writelines(grocery_list) except FileNotFoundError: print("File not found")) Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Seek and tell Python provides two methods for moving around files. The tell() method tells the current position in bytes and the seek(byte_pos) method moves to the position specified. The following code opens the groceries.txt file, reads in a couple of lines, and then uses the tell() method to find the current location. try: grocery_file = open("groceries.txt","r") grocery_list = grocery_file.readline() current_position = grocery_file.tell() print(current_position) grocery_file.close() except FileNotFoundError: pass Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Seek and Find The following code opens the groceries.txt file and uses the seek(byte) method to change the current position in the file. Passing an argument of 0 causes the program to move to the beginning of the file, and the expression seek(0,2) causes the program to move to the end of the file. try: grocery_file = open("groceries.txt","r") grocery_file.seek(45) grocery_item = grocery_file.readline() print(grocery_item) current_position = grocery_file.tell() print(current_position) grocery_file.close() except FileNotFoundError: pass Copyright (c) 2017 by Dr. E. Horvath