CMSC201 Computer Science I for Majors

Similar documents
CMSC201 Computer Science I for Majors

Unit 6. File processing

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC 201 Spring 2016 Lab 08 Strings and File I/O

Introduction to Computer Programming for Non-Majors

Python! Created in 1991 by Guido van Rossum (now at Google)

Before Reading Week. Lists. List methods. Nested Lists. Looping through lists using for loops. While loops

Introduction to Computer Programming for Non-Majors

CSE 142 Sample Final Exam #2

File Processing. CS 112: Introduction to Programming: File Processing Sequence. File Processing. File IO

CMSC 201 Fall 2017 Lab 12 File I/O

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Building Java Programs Sample Final Exam #1. Name of Student. Section (e.g., AA)

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

Chapter 2, Part I Introduction to C Programming

CMSC201 Computer Science I for Majors

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

CMSC201 Computer Science I for Majors

Python Programming: An Introduction to Computer Science

Fundamentals of Programming Session 4

CMSC201 Computer Science I for Majors

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

CMSC201 Computer Science I for Majors

Starting chapter 5. l First open file, and say purpose read or write inputfile = open('mydata.txt', 'r') outputfile = open('myresults.

File input and output and conditionals. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

File processing and decision structures

CMSC201 Computer Science I for Majors

Previously. Iteration. Date and time structures. Modularisation.

CMSC 201 Spring 2017 Lab 05 Lists

C10552: Intro to Computation. Lecture 2 July 17, 2016

Exceptions and File I/O

CMSC 201 Spring 2019 Lab 06 Lists

Script Files and Permissions Ray Lockwood Points: A script is a program made of Unix commands. chmod is the command that changes file permissions

Strings are actually 'objects' Strings

CSE 142 Sample Final Exam #2

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

Loop structures and booleans

File input and output if-then-else. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Programming for Engineers Introduction to C

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Lecture 3. Input, Output and Data Types

CSCA20 Worksheet Working with Files

Part III Appendices 165

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

CMSC 201 Computer Science I for Majors

Introduction to Unix

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Lab 7c: Rainfall patterns and drainage density

CMSC201 Computer Science I for Majors

Scheme: Strings Scheme: I/O

Intro. Scheme Basics. scm> 5 5. scm>

IT 374 C# and Applications/ IT695 C# Data Structures

Previously. Iteration. Date and time structures. Modularisation.

LOOPS. Repetition using the while statement

CS1 Lecture 3 Jan. 18, 2019

CMSC201 Computer Science I for Majors

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

CMSC 201 Fall 2016 Homework 6 Functions

First Java Program - Output to the Screen

CMSC162 Intro to Algorithmic Design II Blaheta. Lab March 2019

Introduction to Computer Programming for Non-Majors

CS1 Lecture 3 Jan. 22, 2018

CS 100: Computability, Python Lists

Get comfortable using computers

Week 2: Data and Output

Eat (we provide) link. Eater. Goal: Eater(Self) == Self()

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

Introduction to Python Code Quality

Getting Started Values, Expressions, and Statements CS GMU

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Introduction to: Computers & Programming: Strings and Other Sequences

Introduction to Unix

Pathologically Eclectic Rubbish Lister

Language Reference Manual

Programming Fundamentals and Python

CMSC201 Computer Science I for Majors

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

CMSC201 Computer Science I for Majors

Sequences: Strings, Lists, and Files

Week Overview. Simple filter commands: head, tail, cut, sort, tr, wc grep utility stdin, stdout, stderr Redirection and piping /dev/null file

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

Functions Defining Calling (invoking) Parameters Returned values

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Civil Engineering Computation

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

CS1 Lecture 9 Feb. 5, 2018

Level 3 Computing Year 2 Lecturer: Phil Smith

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12

Python Day 3 11/28/16

Transcription:

CMSC201 Computer Science I for Majors Lecture 15 File I/O All materials copyright UMBC unless otherwise noted

Last Class We Covered Python s tuple data structure Tuples in functions (and as return values) Basic tuples operations, including Creation Conversion Repetition Slicing Traversing 2

Any Questions from Last Time? 3

Today s Objectives To learn about escape sequences What they are Why we need them How to use them To be able to Open a file Read in its data 4

Escape Sequences 5

Misbehaving print() Function There are times when the print() function doesn t output exactly what we want >>> print("i am 5 feet, 4 inches") I am 5 feet, 4 inches >>> print("i am 5'4"") File "<stdin>", line 1 print("i am 5'4"") ^ SyntaxError: EOL while scanning string literal 6

Special Characters Just like Python has special keywords for, int, True, etc. It also has special characters Single quote ('), double quote ("), etc. 7

Backslash: Escape Sequences The backslash character (\) is used to escape a special character in Python Tells Python not to treat it as special The backslash character goes in front of the character we want to escape >>> print("i am 5'4\"") I am 5'4" 8

Using Escape Sequences There are three ways to solve the problem of printing out our height using quotes >>> print("i am 5'4\"") I am 5'4" >>> print('i am 5\'4"') I am 5'4" >>> print("i am 5\'4\"") I am 5'4" 9

Using Escape Sequences There are three ways to solve the problem of printing out our height using quotes >>> print("i am 5'4\"") I am 5'4" >>> print('i am 5\'4"') I am 5'4" >>> print("i am 5\'4\"") I am 5'4" escape double quotes (using " for the string) escape single quotes (using ' for the string) escape both single and double quotes (works when using ' or ") 10

Common Escape Sequences Escape Sequence Purpose \' Print a single quote \" Print a double quote \\ Print a backslash \t Print a tab \n Print a new line ( enter ) """ Allows multiple lines of text """ is not really an escape sequence, but is useful for printing quotes 11

Escape Sequences Example tabby_cat = "\ti'm tabbed in." print(tabby_cat) I'm tabbed in. \t adds a tab persian_cat = "I'm split\non a line." print(persian_cat) I'm split on a line. \n adds a newline backslash_cat = "I'm \\ a \\ cat." print(backslash_cat) I'm \ a \ cat. \\ adds a single backslash 12 http://learnpythonthehardway.org/book/ex10.html

Escape Sequences Example fat_cat = """ I like to eat: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print(fat_cat) 13 http://learnpythonthehardway.org/book/ex10.html

Escape Sequences Example fat_cat = """ I like to eat: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print(fat_cat) I like to eat: * Cat food * Fishies * Catnip * Grass \t puts in a tab \n adds a newline 14 http://learnpythonthehardway.org/book/ex10.html

Escape Sequences Example fat_cat = """ I like to eat: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print(fat_cat) I like to eat: * Cat food * Fishies * Catnip * Grass when using triple quotes ("""), the times you hit enter inside the string will print as newlines 15 http://learnpythonthehardway.org/book/ex10.html

How Python Handles Escape Sequences Escape sequences look like two characters to us Python treats them as a single character example1 = "dog\n" example2 = "\tcat" 0 1 2 3 d o g \n 0 1 2 3 \t c a t 16

File Input and Output 17

Why Use Files? Until now, the Python programs you've been writing use pretty simple input and output User types input at the keyboard Results (output) are displayed in the console This is fine for short and simple input But what if we want to average 50 numbers, and mess up when entering the 37th one? Start all over??? 18

What is File I/O? One solution is to read the information in from a file on your computer You can even write information to a file This process is called File I/O "I/O" stands for "input/output Python has built-in functions that make this easy 19

File I/O Example: Word Processor Reading in a file using a word processor File opened from hard disk Contents read into memory (RAM) File closed on hard disk IMPORTANT: Changes to the file are made to the copy stored in memory, not the original file on the disk 20

hard disk RAM 21 1. File opened from hard disk 2. Contents read into memory (RAM) 3. File closed from hard disk 4. Changes are saved to the copy in memory

File I/O Example: Word Processor Writing a file using a word processor (Saving a word processing file) Original file on the disk is reopened in a mode that will allow writing This actually erases the old contents! Copy the version of the document stored in memory to the original file on disk File is closed 22

hard disk RAM 23 1. File opened on hard disk for writing 2. (Old contents are erased!) 3. Copy version in memory to hard disk 4. Close file on hard disk

File Processing In order to do interesting things with files, we need to be able to perform certain operations: Associate an external file with a program object Opening the file Manipulate the file object Reading from or writing to the file object Close the file Making sure the object and file match at the end 24

Opening a File 25

Syntax for open() Function myfile = open(file_name [, access_mode]) file_name This argument is a string the contains the name of the file you want to access "input.txt" "numbers.dat" "roster.txt" 26

Syntax for open() Function myfile = open(file_name [, access_mode]) access_mode (optional argument) This argument is a string that determines which of the modes the file is to be opened in "r" (open for reading) "w" (open for writing) "a" (open for appending) 27

Examples of Using open() In general, we will use commands like: myfile = open("scores.txt") datain = open("stats.dat", "r") dataout = open("stats2.dat", "w") an example input file scores.txt 2.5 8.1 7.6 3.2 3.2 3.0 11.6 6.5 2.7 12.4 8.0 8.0 8.0 8.0 7.5 28

Reading in a File 29

Using File Objects to Read Files myfile = open("mystuff.txt") This line of code does three things: 1. Opens the file mystuff.txt 2. In reading mode (which is the default) 3. Assigns the opened file to the variable myfile Once the file is open and assigned to a variable, we can start reading it 30

Three Ways to Read a File There are three different ways to read in a file: 1. Read the whole file in as one big long string myfile.read() 2. Read the file in one line at a time myfile.readline() 3. Read the file in as a list of strings (each is one line) myfile.readlines() 31

Entire Contents into One String >>> info = open("hours.txt") >>> wholething = info.read() >>> wholething it s literally one giant string! '123 Susan 12.5 8.1 7.6 3.2\n456 Brad 4.0 11.6 6.5 2.7 12\n789 Jenn 8.0 8.0 8.0 8.0 7.5\n' our input file hours.txt 123 Suzy 9.5 8.1 7.6 3.1 3.2 456 Brad 7.0 9.6 6.5 4.9 8.8 789 Jenn 8.0 8.0 8.0 8.0 7.5 32 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

Entire Contents into One String >>> info = open("hours.txt") >>> wholething = info.read() >>> wholething it s literally one giant string! '123 Susan 12.5 8.1 7.6 3.2\n456 Brad 4.0 11.6 6.5 2.7 12\n789 Jenn 8.0 8.0 8.0 8.0 7.5\n' notice the escape sequence (\n) is being printed, instead of the text starting on a new line our input file hours.txt 123 Suzy 9.5 8.1 7.6 3.1 3.2 456 Brad 7.0 9.6 6.5 4.9 8.8 789 Jenn 8.0 8.0 8.0 8.0 7.5 33 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

One Line at a Time >>> info = open("hours.txt") >>> lineone = info.readline() >>> lineone '123 Susan 12.5 8.1 7.6 3.2\n' >>> linetwo = info.readline() '456 Brad 4.0 11.6 6.5 2.7 12\n' there s actually an easier way to do this can you guess what it is? (we ll show you soon) our input file hours.txt 123 Suzy 9.5 8.1 7.6 3.1 3.2 456 Brad 7.0 9.6 6.5 4.9 8.8 789 Jenn 8.0 8.0 8.0 8.0 7.5 34 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

As a List of Strings >>> info = open("hours.txt") >>> listoflines = info.readlines() >>> listoflines ['123 Susan 12.5 8.1 7.6 3.2\n', '456 Brad 4.0 11.6 6.5 2.7 12\n', '789 Jenn 8.0 8.0 8.0 8.0 7.5\n'] our input file hours.txt 123 Suzy 9.5 8.1 7.6 3.1 3.2 456 Brad 7.0 9.6 6.5 4.9 8.8 789 Jenn 8.0 8.0 8.0 8.0 7.5 35 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

Using for Loops to Read in Files Remember, for loops are great for iterating With a list, the for loop iterates over Each element of the list (in order) Using a range(), the for loop iterates over Each number generated by the range (in order) And with a file, the for loop iterates over Each line of the file (in order) 36

A Better Way to Read One Line at a Time Instead of reading them manually, use a for loop to iterate through the file line by line >>> info = open("hours.txt") >>> for eachline in info:... print(eachline)... 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jenn 8.0 8.0 8.0 8.0 7.5 37

A Better Way to Read One Line at a Time Instead of reading them manually, use a for loop to iterate through the file line by line 38 >>> info = open("hours.txt") >>> for eachline in info:... print(eachline)... 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jenn 8.0 8.0 8.0 8.0 7.5 why are there all these empty lines??? now that we re calling print(), the \n is printing out as a second new line

Whitespace 39

Whitespace Whitespace is any blank character, that represents space between other characters For example: tabs, newlines, and spaces "\t" "\n" " " When we read in a file, we can get whitespace Sometimes, we don t want to keep it 40

Removing the Newline from the End To remove the escaped newline sequence (\n) from a string we read in, we can use slicing mystring = mystring[:-1] 0 1 2 3 d o g \n 41-4 -3-2 -1 mystring

Removing the Newline from the End To remove the escaped newline sequence (\n) from a string we read in, we can use slicing mystring = mystring[:-1] 42 don t remove anything from the beginning just remove the very last character 0 1 2 3 d o g \n -4-3 -2-1 mystring

Removing Whitespace To remove all whitespace from the start and end of a string, we can use strip() spacedout = spacedout.strip() \t c a t s \n 43 spacedout

Removing Whitespace To remove all whitespace from the start and end of a string, we can use strip() spacedout = spacedout.strip() \t c a t s \n 44 spacedout

Removing Whitespace To remove all whitespace from the start and end of a string, we can use strip() spacedout = spacedout.strip() notice that strip() does not remove interior spacing \t c a t s \n 45 spacedout

Miscellaneous (and Exercises!) 46

Getting a Filename from a User Instead of putting the filename straight in the code, we can ask the user for the filename Save their response in a variable, and call the open() function with it # printfile.py # Prints a file to the screen. def main(): fname = input("enter filename: ") infile = open(fname, 'r') data = infile.read() print(data) 47 main()

Exercise: Jabberwocky Write a program that goes through a file and reports the longest line in the file Example Input File: caroll.txt Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch. Example Output: >>> longest.py longest line = 42 characters the jaws that bite, the claws that catch, 48

Jabberwocky Solution Pseudocode inside main: open the file "carroll.txt" (for reading) create a variable to store the "longest" line # we'll refer to this variable as "record" # what should this variable be initialized to? for each line of the input if the current line is longer than the record update the record to the current line print the length of the longest line print the longest line call main 49

Jabberwocky Solution Code def main(): inputfile = open("carroll.txt") longest = "" for line in inputfile: if len(line) > len(longest): longest = line main() print("longest line =", len(longest)) print(longest) 50

Jabberwocky Solution Walkthrough line = Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch. line = "Beware the Jabberwock, my son," longest = "" longest = "Beware the Jabberwock, my son," 51 len(line) > len(longest) 31 > 0 for line in inputfile: if len(line) > len(longest): longest = line

Jabberwocky Solution Walkthrough line = Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch. line = "the jaws that bite, the claws that catch," longest = "" longest = "Beware the Jabberwock, my son," longest = "the jaws that bite, the claws that catch," 52 len(line) > len(longest) 42 > 31 for line in inputfile: if len(line) > len(longest): longest = line

Jabberwocky Solution Walkthrough line = Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch. line = "Beware the JubJub bird and shun" longest = "" longest = "Beware the Jabberwock, my son," longest = "the jaws that bite, the claws that catch," 53 len(line) > len(longest) 32 > 42 for line in inputfile: if len(line) > len(longest): longest = line

Jabberwocky Solution Walkthrough line = Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch. line = "the frumious bandersnatch." longest = "" longest = "Beware the Jabberwock, my son," longest = "the jaws that bite, the claws that catch," 54 len(line) > len(longest) 27 > 42 for line in inputfile: if len(line) > len(longest): longest = line

Announcements Homework 7 is due Wednesday Project 1 comes out this week It will be difficult No collaboration allowed! Start early! Think before you code! Come to office hours! 55