Strings, Lists, and Files

Slides:



Advertisements
Similar presentations
File AccessCS-2301, B-Term File Access CS-2301, System Programming for Non-Majors (Slides include materials from The C Programming Language, 2 nd.
Advertisements

1 CS150 Introduction to Computer Science 1 Professor: Chadd Williams
Accessing Files in CCS-2303, C-Term Accessing Files in C CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Working with Files CSC 161: The Art of Programming Prof. Henry Kautz 11/9/2009.
Computer Systems Week 10: File Organisation Alma Whitfield.
Lists in Python.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Files Tutor: You will need ….
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])
File Systems - Part I CS Introduction to Operating Systems.
Python Programing: An Introduction to Computer Science
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
String and Lists Dr. José M. Reyes Álamo.
EET 2259 Unit 13 Strings and File I/O
Chapter 2: Introduction to C++
File I/O File input/output Iterate through a file using for
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.
Containers and Lists CIS 40 – Introduction to Programming in Python
Python’s input and output
CS190/295 Programming in Python for Life Sciences: Lecture 1
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
File I/O File input/output Iterate through a file using for
First Python Program Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An.
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
String and Lists Dr. José M. Reyes Álamo.
Decision Structures and Indefinite Loops
Introduction to Dictionaries
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Elements of a Python Program
More About Functions Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An.
Variables, Lists, and Objects
Debuggers and Debugging
Simple Graphics Package
Objects (again) Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction.
More elements of Python programs
Notes about Homework #4 Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming:
Files Handling In today’s lesson we will look at:
Fundamentals of Python: First Programs
CSV files Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction.
Note on Program Design Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming:
Notes on Homework #6 Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An.
CS190/295 Programming in Python for Life Sciences: Lecture 3
15-110: Principles of Computing
15-110: Principles of Computing
Topics Introduction to File Input and Output
Introduction to Computer Science
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
EET 2259 Unit 13 Strings and File I/O
Microsoft Office Illustrated Fundamentals
Topics Introduction to File Input and Output
Numpy, pylab, matplotlib (follow-up)
Introduction to Computer Science
Presentation transcript:

Strings, Lists, and Files Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction to Computer Science, 2nd edition, by John Zelle and copyright notes by Prof. George Heineman of Worcester Polytechnic Institute) CS-1004, A-Term 2014 Strings, Lists, and Files

Reading Assignment Chapter 5:– Sequences I.e., Strings, Lists, and Files CS-2301, D-Term 2014 Introduction

What is a String? String literal:– Any piece of text enclosed in matching quotes May be single or double quotes “This sentence, of course, is written in English.” ‘Esta frase se escrita en español.’ ‘Wir können auch in Deutsch und Französisch zu schreiben‘ “En fait, nous pouvons écrire les chaînes en Python en japonais, aussi.” ‘Pythonはあっても、私たちは日本語などのアジアの言語で書くことができます。’ Anything that you can type in ANY language can be represented and stored as a string in Python! Unicode standard CS-2301, D-Term 2014 Introduction

String literal (continued) A string literal is a constant, … … just like a numerical value Example:– S = 'This is a string!' The name S refers to the value ‘This is a string!’ Without the quotes Quotes must be paired Either single or double CS-2301, D-Term 2014 Introduction

Operations on Strings + — concatenation * — repetition [] — indexing S = "This is a string" T = "and this is a another string" U = S + ', ' + T + '.' What is the value of U? * — repetition Y = "yuck, yuckity, " Y * 5 [] — indexing Like lists S[0] T[1] U[2] U[-1] U[-2] CS-2301, D-Term 2014 Introduction

Operations on Strings (continued) Slicing I.e., taking a subset of a string S = "This is a string" T = S[5:7] Special cases U1 = S[-7:-1] U2 = S[-7:] U3 = S[:-7] ... Starting position of substring End of substring — This character is not included CS-2301, D-Term 2014 Introduction

Operations on Strings (continued again) len(S) — length of string in characters for c in S: Iterate thru the characters of the string S ord('c') Get the Unicode character number of c 'c' must be a string of length 1 chr(int) Return a string containing a single character, the ord of which is int CS-2301, D-Term 2014 Introduction

Useful string methods s.capitalize() s.count(sub) s.find(sub) Count occurrences of a substring s.find(sub) Find a substring s.strip([chars]) Removes designated characters from string s.replace(old, new) Replaces instances of old substring with new substring … All return a (modified) copy of string Do not update original string CS-2301, D-Term 2014 Introduction

Lists have methods, too! l.append() l.sort() l.reverse() Our friend l.sort() Sorts elements in place. May be high-to-low or low- to-high l.reverse() Reverses the list l.index(x) l.count(x) Returns index of first occurrence of x in list or count of x’s in list l.pop(i) l.remove(x) Removes ith element (pop) or first occurrence of x See p. 345, also Python documentation CS-2301, D-Term 2014 Introduction

Questions? CS-2301, D-Term 2014 Introduction

Definition — File A (potentially) large amount of information that lives a (potentially) very long time May be (much) larger than the amount of RAM in your computer (Usually) expected to outlive the running of your program (May be) expected to outlive the computer itself! Stored on Hard drive Flash drive Spread out across multiple disks Somewhere in the “cloud” On some other medium … CS-2301, D-Term 2014 Introduction

Files (continued) (Usually) stored as a sequence of bytes Byte: an 8-bit character The standard unit of storage since 1964 Other data types built up from sequences of bytes Organization of data within file defined by application Text Numerical data Big databases Program code … Directory (a.k.a. folder) — a list names and locations of other files Maintained by operating system CS-2301, D-Term 2014 Introduction

Remember to close your files before exiting your program! Using Files Must be Opened before use Tells OS to make file ready for access Must be Closed when finished Tells OS to “put the file away” Make it safe for long term storage Note: Most operating systems automatically close files that are still open when program exits Don’t depend on this! Stale data may live in volatile memory for long time Where it can become corrupted … … or forgotten … … or lost … before OS gets around to writing to disk! Remember to close your files before exiting your program! CS-2301, D-Term 2014 Introduction

Three other modes:–. 't' – text mode (default). 'b' – binary Three other modes:– 't' – text mode (default) 'b' – binary '+' – update in place Open Gets a file read for use OS sets up internal tables May fetch copy off remote disk Validates protection, Etc. f = open(filename, mode) Built-in function Filename String of text Name of the file (as seen in directory), with extension Possibly including directory “path” Mode 'r' – read (default) 'w' – write (truncate to zero length) 'a' – append … (other modes — see Python documentation) CS-2301, D-Term 2014 Introduction

Close f.close() = open(filename, mode) File method Closes the file Clears internal buffers I.e., puts it away safely Don’t forget to do this in your program! CS-2301, D-Term 2014 Introduction

Reading from files f = open(filename, mode) f.read() Reads entire remaining contents of file into one (potentially humungous) string Line endings represented by '\n' characters “Remaining” means from where we left off reading most recently to end of file f.readline() Reads one line Including '\n' character (a.k.a. newline character) Returns line as a string f.readlines() Reads all of the lines Returns a list of strings Each representing one line — as from readline() CS-2301, D-Term 2014 Introduction

Reading from files (continued) Homework #4 requires you to read multiple files Process each one More useful information about file reading:– §5.9.2 of textbook Chapter 7 of online Python tutorial In IDLE, select Help > Python Docs Click Contents tab, select The Python Tutorial Click Input and Output About 7 lines down! CS-2301, D-Term 2014 Introduction

Homework #4 Once you have opened a file, need to extract all of the individual words Add to a list How to do that? Questions? CS-2301, D-Term 2014 Introduction

Writing to a file Also required in Homework #4 f = open(outputfilename, 'w') f.write(string) Writes the string at the end of the file Returns number of bytes written You need to supply trailing '\n' character To denote end of line You may write partial lines i.e., with no trailing '\n' You may write multiple lines at one time Until you are more skilled, concentrate on writing one full line at a time! CS-2301, D-Term 2014 Introduction

What next? Close the file! Note:– both Python and OS keep contents of file buffered in memory I.e., volatile memory! Closing flushes the buffers to disk Where it is stored safe from (most) failures CS-2301, D-Term 2014 Introduction

Questions? CS-2301, D-Term 2014 Introduction