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

Similar documents
File I/O in Python CS 8: Introduction to Computer Science Lecture #11

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

More on Lists, Dictionaries Introduction to File I/O CS 8: Introduction to Computer Science Lecture #10

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Review for the Final Exam CS 8: Introduction to Computer Science, Winter 2018 Lecture #15

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

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

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science, Winter 2018 Lecture #9

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

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

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Functions and the MIPS Calling Convention 2 CS 64: Computer Organization and Design Logic Lecture #11

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Function Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

Using the MIPS Calling Convention. Recursive Functions in Assembly. CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

MIPS Assembly: Practice Questions for Midterm 1 Saving to and Loading from Memory CS 64: Computer Organization and Design Logic Lecture #6

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science Lecture #7

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Introduction to Computer Programming for Non-Majors

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017

CS1 Lecture 12 Feb. 11, 2019

Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Welcome to Solving Problems with Computers I

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Dynamic Arrays Makefiles and Mul3ple File Compiles

File I/O CS 16: Solving Problems with Computers I Lecture #9

Reviewing all Topics this term

MIPS Assembly: More about Memory and Instructions CS 64: Computer Organization and Design Logic Lecture #7

File processing and decision structures

Welcome to Computer Organization and Design Logic

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Functions Defining Calling (invoking) Parameters Returned values

More Examples Using Lists Tuples and Dictionaries in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #11

Welcome to Computer Organization and Design Logic CS 64: Computer Organization and Design Logic Lecture #1 Winter 2018

Scientific Computing: Lecture 3

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Introduction to Computer Programming for Non-Majors

Reversing. Time to get with the program

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

PROGRAMMING, DATA STRUCTURES AND ALGORITHMS IN PYTHON

Files. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Principles of Computer Science I

CS1 Lecture 2 Jan. 16, 2019

MIPS and Basic Assembly Language CS 64: Computer Organization and Design Logic Lecture #4

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

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

Announcements COMP 141. Writing to a File. Reading From a File 10/18/2017. Reading/Writing from/to Files

Python Lists and Dictionaries CS 8: Introduction to Computer Science, Winter 2019 Lecture #13

Topic: List processing (with application to files)

CS 112: Intro to Comp Prog

More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

Unit 7: Algorithms and Python CS 101, Fall 2018

Python, Part 2 CS 8: Introduction to Computer Science Lecture #4

Binary Arithmetic CS 64: Computer Organization and Design Logic Lecture #2 Fall 2018

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

CS 132 Exam #1 - Study Suggestions

MIPS Instruc,ons CS 64: Computer Organiza,on and Design Logic Lecture #8

Call- by- Reference Func0ons Procedural Abstrac0ons Numerical Conversions CS 16: Solving Problems with Computers I Lecture #9

MIPS Assembly: More about MIPS Instructions Using Functions in MIPS CS 64: Computer Organization and Design Logic Lecture #8

CS Introduction to Programming Fall 2016

Computer Science II Lecture 1 Introduction and Background

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Topic 6: A Quick Intro To C

C++ Programming Lecture 10 File Processing

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

Files on disk are organized hierarchically in directories (folders). We will first review some basics about working with them.

Caches II. CSE 351 Spring Instructor: Ruth Anderson

San José State University Department of Computer Science CS-144, Advanced C++ Programming, Section 1, Spring 2018

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

This exam has 10 pages including the title page. Please check to make sure all pages are included.

Computer Science II Data Structures

Loop structures and booleans

Python Lists 2 CS 8: Introduction to Computer Science Lecture #9

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Introduction to Computer Science. Course Goals. Python. Slides02 - Intro to Python.key - September 15, 2015

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

#11: File manipulation Reading: Chapter 7

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Pre- Defined Func-ons in C++ Review for Midterm #1

Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9

San José State University Computer Science CS 122 Advanced Python Programming Spring 2018

University of Texas at Arlington, TX, USA

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

MIPS and Basic Assembly Language CS 64: Computer and Design Logic Lecture #4

MICROPROCESSORS A (17.383) Fall Lecture Outline

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

Introduction to programming using Python

7/21/10 MOTIVATION. Did you see Inception this weekend? COMP 10 EXPLORING COMPUTER SCIENCE. Lecture 6 Arrays

Transcription:

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12 Ziad Matni Dept. of Computer Science, UCSB

Administrative Homework #7 is DUE on MONDAY (3/12) Lab #5 will be out soon and due Wed 3/7 Remaining on the calendar This supersedes anything on the syllabus DATE TOPIC ASSIGNED DUE Mon. 3/5 Wed. 3/7 File I/O ; Formats for Outputs Digital Images ; While-Loops Hw #7 Lab #5 Mon. 3/13 Recursive Functions Hw #8 Wed. 3/15 Review for the Final Exam Lab #6 Hw #6 Lab #5 Hw #7, Hw #8 Lab #6 Proj #2 3/5/18 Matni, CS8, Wi18 2

Chapter 5 File I/O in Python How to Demos Lecture Outline Reading file over the Internet Formats for outputs 3/5/18 Matni, CS8, Wi18 3

Starting Chapter 5 Files Mostly handle like any sequential data type A sequence of characters if a text file, or a sequence of bytes if a binary file Can you name some file types that are textual? Or binary? 3/5/18 Matni, CS8, Wi18 4

Why Use Files? 4 Good Reasons: Files allow you to store data permanently and conveniently! Data output to a file lasts after the program ends You can usually view them without the need of a Python program An input file can be used over and over No typing of data again and again for testing Files allow you to deal with larger data sets 3/5/18 Matni, CS8, Wi18 5

Input and Output in Computers Recall input and output are 2 of the main components of a computer There are different types of I/O What we call standard output is usually the screen What we call standard input is usually the keyboard But there ARE other ways to get I/O Like using files to write to (output) or to read from (input) 3/5/18 Matni, CS8, Wi18 6

File I/O: Examples of How To Example of READING from a file filename = input ("What is the name of the file to open? ") InFile = open(filename, 'r') count = 0 for line in InFile: count += 1 print(line) print("there are ", count, " lines in the file ", filename) Example of WRITING to a file filename = input ("What is the name of the file to open? ") OutFile = open(filename, 'w') for n in range(10): myfile.write('number ', n) OutFile.close() InFile.close() 3/5/18 Matni, CS8, Wi18 7

Read File Example of READING from a file filename = input ("What is the name of the file to open? ") InFile = open(filename, 'r') count = 0 for line in InFile: count += 1 print(line) print("there are ", count, " lines in the file ", filename) InFile.close() open() function, using the r option means that we want to READ this file. Note that filename is a string. This is what we re doing to the lines that we read from the file. Note that the use of the print() function here means that the output goes to standard output (i.e. your screen) Always close() the file after opening it! Alternative instruction: InFile = open(filename, 'r', encoding='utf-8') 3/5/18 Matni, CS8, Wi18 8

Write File Example of WRITING to a file filename = input ("What is the name of the file to open? ") OutFile = open(filename, 'w') for n in range(10): myfile.write('number ', n) OutFile.close() open() function, using the w option means that we want to WRITE to this file. Note that filename is a string. This is the data that we re creating to put into the file. Note that the use of the write() function here means that the output goes to file output (not standard output ) Always close() the file after opening it! 3/5/18 Matni, CS8, Wi18 9

More Ways To Read A File Already saw: for line in file to process each line as a separate string (including '\n' at ends of each line) To get just a single line (as a string): file.readline() Do it again to get the next line, and so on Also can get a list of all lines (again, as strings) by using file.readlines() This includes '\n' at ends of each line Note readlines vs readline DEMO! Let s try it! 3/5/18 Matni, CS8, Wi18 10

More Ways To Read A File You can also just file.read() to get all of the file s text as a single string Note: use open() again if want to go back to the beginning of a file and read from start 3/5/18 Matni, CS8, Wi18 11

Summary of Different Ways to Read file.readline() Reads ONE line (as a string) file.readlines() Reads ALL lines (as a list of strings) file.read() Reads ALL lines (as one giant string) 3/5/18 Matni, CS8, Wi18 12

Demonstration Given: An input file with information on rainfall (in inches) for various geographical locations. Looks like this: Akron 25.81 Albia 37.65 etc You have to: Create an output file that reads each line and outputs: Akron had 25.81 inches of rain. Albia had 37.65 inches of rain. etc See rainfall.py and rainfall_advanced.py 3/5/18 Matni, CS8, Wi18 13

Reading a File Over the Internet Instead of reading a file that s in the same directory (i.e. local), you can read a file that s on the Internet (i.e. remote) Need a properly-formatted Uniform Resource Locator (URL) string then you can open the remote file: import urllib.request urlname = 'http://www.cs.ucsb.edu' file = urllib.request.urlopen(urlname) urlcontent = file.read().decode('utf-8') 3/5/18 Matni, CS8, Wi18 14

Reading a File Over The Internet Now treat it almost like any file open for reading: for line in file: # not okay to do it is not iterable oneline = file.readline() # use this to read ONE line alllines = file.readlines() # use this to read ALL lines alltext = file.read() # use this to read ALL lines See getwebpage.py 3/5/18 Matni, CS8, Wi18 15

3/5/18 Matni, CS8, Wi18 16

Formatting Output Lines 1 Applies whether for output to standard (i.e. display) or to a file All file I/O are considered strings BY DEFAULT, so you may have to do some conversions if you want them to be used as integers or float (e.g. to be able to do numerical calculations) Example: num = int( infile.readline( ) ) # the file I m reading has lines of just integers # I want to ensure that these inputs will be used as int doublenum = num * 2 3/5/18 Matni, CS8, Wi18 17

Formatting Output Lines 2 You can use a Python template called formatted strings Uses an operator % In the context of its use this IS NOT THE MODULO OPERATOR! For example, instead of: print( My friend, FriendName, is, age, years old ) you can do: print( My friend %s is %d years old % (FriendName, age)) %s = a string goes here %d = an integer goes here 3/5/18 Matni, CS8, Wi18 18

Why Do This? Because we can easily use format modifiers print( My friend %s is %5d years old % (FriendName, age)) This example puts the value of variable age in a field width of 5 spaces My friend John is 33 years old 5 spaces 3/5/18 Matni, CS8, Wi18 19

Format Modifiers: More Examples See Tables 5.2 & 5.3 in Textbook >>> print( These %d bottles of beer on the wall % 99) These 99 bottles of beer on the wall >>> n = 4 >>> cost = 0.5 >>> print ( %d items, each for $%.2f % (n, cost)) 4 items, each for $0.50 >>> name = Mr. Bojangles >>> print ( Hello, %s, how are you?! % (name)) %s - String (or any object with a string representation, like numbers) %d - Integers %f - Floating point numbers %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. 3/5/18 Matni, CS8, Wi18 20

New Way: Using.format Similar ideas, different syntax: >>> "{1} has ${0}".format(42,'Joe') 'Joe has $42.00 >>> "{1} has ${0:.2f}".format(42,'Joe') 'Joe has $42.00' >>> "{0} is {age} years old".format('edward',age=20) 'Edward is 20 years old' 3/5/18 Matni, CS8, Wi18 21

New Way: Using.format Keyword arguments are handy, Especially if there are lots of arguments More information can be found at: http://www.python-course.eu/python3_formatted_output.php (but, alas, not in our text book) THIS WEBSITE MATERIAL IS REQUIRED READING 3/5/18 Matni, CS8, Wi18 22

q Next: Chapter 6 YOUR TO-DOs q Start working on HW # 7, Lab # 5 q Keep working on Project2 (due Friday 3/16) 3/5/18 Matni, CS8, Wi18 23

3/5/18 Matni, CS8, Wi18 24