Last Class We Covered Escape sequences File I/O Uses a backslash (\)

Slides:



Advertisements
Similar presentations
Unit 6 File processing Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except where otherwise.
Advertisements

Computer Science 111 Fundamentals of Programming I Files.
Week 7 Lists Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed.
1 Scanning Tokens. 2 Tokens When a Scanner reads input, it separates it into “tokens”  … at least when using methods like nextInt()  nextInt() takes.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
File I/O Michael Ernst UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
File I/O Ruth Anderson UW CSE 160 Spring File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Unit 6 File processing Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except where otherwise.
File I/O Ruth Anderson UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Input, Output and Variables GCSE Computer Science – Python.
CMSC201 Computer Science I for Majors Lecture 12 – Midterm Review Prof. Katherine Gibson.
CMSC201 Computer Science I for Majors Lecture 11 – File I/O (Continued) Prof. Katherine Gibson Based on concepts from:
Prof. Katherine Gibson Prof. Jeremy Dixon
CMSC201 Computer Science I for Majors Lecture 08 – Lists
CMSC201 Computer Science I for Majors Lecture 10 – File I/O
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Topic: File Input/Output (I/O)
Introduction to Python
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
CSC 131: Introduction to Computer Science
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CPS120: Introduction to Computer Science
CSc 120 Introduction to Computer Programing II
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
CMSC202 Computer Science II for Majors Lecture 08 – Overloaded Constructors Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Variables, Expressions, and IO
Last Class We Covered File I/O How to open a file
CSC 108H: Introduction to Computer Programming
CMSC201 Computer Science I for Majors Lecture 27 – Final Exam Review
Ruth Anderson UW CSE 160 Winter 2016
CMSC201 Computer Science I for Majors Lecture 09 – Strings
Engineering Innovation Center
Exceptions and files Taken from notes by Dr. Neil Moore
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Ruth Anderson UW CSE 160 Winter 2017
while loops; file I/O; introduction to lists
Strings Part 2 Taken from notes by Dr. Neil Moore
String Input ICS 111: Introduction to Computer Science I
Topics Introduction to File Input and Output
CSS 161 Fundamentals of Computing Introduction to Computers & Java
File IO and Strings CIS 40 – Introduction to Programming in Python
Learning to Program in Python
Exceptions and files Taken from notes by Dr. Neil Moore
CMSC201 Computer Science I for Majors Lecture 12 – Tuples
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
String and Lists Dr. José M. Reyes Álamo.
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
CMSC201 Computer Science I for Majors Lecture 25 – Final Exam Review
How to save information in files open, write, close
Reading and Writing Files
CMSC201 Computer Science I for Majors Lecture 13 – File I/O
Last Class We Covered File I/O How to open a file
Nate Brunelle Today: Strings, Type Casting
CMSC201 Computer Science I for Majors Final Exam Information
Topics Introduction to File Input and Output
CSE 231 Lab 5.
Topics Introduction to File Input and Output
CMSC201 Computer Science I for Majors Lecture 19 – Dictionaries
Strings Part 2 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
How to read from a file read, readline, reader
Introduction to Computer Science
Getting Started in Python
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

CMSC201 Computer Science I for Majors Lecture 17 – File I/O (Continued)

Last Class We Covered Escape sequences File I/O Uses a backslash (\) How to open a file For reading or writing How to read lines from a file The split() function To break a string into tokens

Any Questions from Last Time?

Today’s Objectives To review how to open and read from a file To learn the join() function “Opposite” of the split() function To get more practice with File I/O To cover the different ways to write to a file To learn how to close a file

Review from Last Class

Using open() Which of these are valid uses of open()? myFile = open(12, "r") fileObj = open("HELLO.txt") writeTo = open(fileName, "w") "file" = open("test.dat", "R") theFile = open("file.dat", "a")

     Using open() Which of these are valid uses of open()? myFile = open(12, "r") fileObj = open("HELLO.txt") writeTo = open(fileName, "w") "file" = open("test.dat", "R") theFile = open("file.dat", "a") not a valid string    uppercase “R” is not a valid access mode not a valid variable name  

Three Ways to Read a File Write the code that will perform each of these actions using a file object called fileIn Read the whole file in as one big long string Read the first line of the file Read the file in as a list of strings (each is one line)

Three Ways to Read a File Write the code that will perform each of these actions using a file object called fileIn Read the whole file in as one big long string bigString = fileIn.read() Read the first line of the file firstLine = fileIn.readline() Read the file in as a list of strings (each is one line) stringList = fileIn.readlines()

Whitespace There are two ways we know of to remove whitespace from a string The strip() function removes all leading and trailing whitespace (tabs, spaces, newlines) from a string withoutWhitespace = myLine.strip() The split() function can be used to remove all whitespace (including interior), creating a list of strings tokens = myLine.split()

Splitting and Joining

Review: String Splitting The split() function can be used in two ways: Break the string up by its whitespace Break the string up by a specific character Both methods take in a single string, and return a list of one or more strings >>> names = "Avery Ben Chetra Emily" >>> names.split() ['Avery', 'Ben', 'Chetra', 'Emily']

Joining Strings We can also join a list of strings back together! The syntax is very different from split() And it only works on a list of strings "X".join(list_of_strings) function name the list of strings we want to join together the delimiter (what we will use to join the strings)

Example: Joining Strings >>> names = ['Alice', 'Bob', 'Carl', 'Dana', 'Eve'] >>> "_".join(names) 'Alice_Bob_Carl_Dana_Eve' We can also use more than one character as our delimiter if we want >>> " <3 ".join(names) 'Alice <3 Bob <3 Carl <3 Dana <3 Eve'

Practice: Joining Use join() to solve the following problems From grades, create a string that looks like "A+, A, A-, B+, B, B-, C+, C, C-, D, F" From acronyms, create a string that looks like "OMG BRB LOL BBQ IDK BFF JK OMW FYI"

Splitting into Variables

Known (Formatted) Input Known input means that we know how the data inside a file will be formatted (laid out) For example, in workerHours.txt, we have: The employee ID number The employee’s name The hours worked over five days workerHours.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 https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

Splitting into Variables If we know what the input will look like, we can split() them directly into different variables var1, var2, var3 = threePartString.split() all of the variables we want to split the string into the string whose input we know, and are splitting on we can have as many different variables as we want https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

Example: Splitting into Variables >>> s = "Jessica 31 647.28" >>> name, age, money = s.split() >>> name 'Jessica' >>> int(age) 31 >>> float(money) 647.28 we may want to convert some of them to something that’s not a string https://courses.cs.washington.edu/courses/cse142/11au/python/06-files.ppt

Writing to Files

Opening a File for Writing Use open() just like we do for reading Provide the filename and the access mode fileObj = open("output.txt", "w") Opens the file for writing Wipes the contents! fileObj = open("myNotes.txt", "a") Opens the file for appending Writes new data to the end of the file

Writing to a File Once a file has been opened, we can write to it What do you think the function to write is called? myFile.write( "hello world!" ) We can also use a string variable in write() myFile.write( writeString )

Details About write() write() only writes exactly what it’s given! This means whitespace (like "\n") is up to you Unlike print(), which adds a newline for you myFile = open("greeting.dat", "w") myFile.write("Hello\nWorld\n") myFile.close()

Word of Caution Write can only take one string at a time! These won’t work: fileObj.write("hello", "my", "name") fileObj.write(17) But this will: fileObj.write("hello" + " my " + "name") fileObj.write(str(17)) Why don’t these work? the first is multiple strings the second is an int, not a string Why does this work? concatenation creates one string casting turns the int into a string

Closing a File Once we are done with our file, we close it We do this for all files – ones that we opened for writing, reading, or appending! myFileObject.close() Properly closing the file is important – why? It ensures that the file is saved correctly

Time for… LIVECODING!!!

deSpacing Write a function that Reads in from a file called “spaced.txt” Counts how many whitespace (\n, \t, and ' ') characters it has Prints out the total count of whitespace characters Creates a new file without any of the whitespace characters (called “unspaced.txt”)

deSpacing: Output File: Available in Dr. Gibson’s pub directory /afs/umbc.edu/users/k/k/k38/pub/cs201/spaced.txt Lots of tabs and spaces Output: bash-4.1$ python spaced.py There were 44 spacing characters in the file How now brown cow Space I like space

Announcements Project 2 out on Blackboard Final exam is when? Design due Friday, April 14th @ 8:59:59 PM Project due Friday, April 21st @ 8:59:59 PM Uses 3D lists and file I/O Final exam is when? Friday, May 19th from 6 to 8 PM