Python Simple file reading

Slides:



Advertisements
Similar presentations
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
While loops.
Computer Science 1620 Loops.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
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.
5.05 Apply Looping Structures
Python Control of Flow.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Control Structures. Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Python Tricks CMSC 201. Overview Today we are learning some new tricks to make our lives easier! Slicing and other tricks Multiple return values Global.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
Python Let’s get started!.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
JavaScript: Conditionals contd.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
JavaScript Controlling the flow of your programs with ‘if’ statements
G. Pullaiah College of Engineering and Technology
CSC 352– Unix Programming, Spring 2016, Final Exam Guide
REPETITION CONTROL STRUCTURE
EECS 183 Discussion #9: It’s time to “Git” Python! November 22nd, 2016
Python Loops and Iteration
Python Let’s get started!.
Introduction to Python
Making Choices with if Statements
Introduction To Repetition The for loop
Python: Control Structures
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
CS1371 Introduction to Computing for Engineers
CS 115 Lecture 8 Structured Programming; for loops
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Programming – Touch Sensors
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Writing Functions( ) (Part 5)
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
More Selections BIS1523 – Lecture 9.
Python Primer 2: Functions and Control Flow
File Handling Programming Guides.
Topics Introduction to File Input and Output
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
CISC101 Reminders Slides have changed from those posted last night…
Using files Taken from notes by Dr. Neil Moore
CISC101 Reminders Assn 3 due tomorrow, 7pm.
CISC101 Reminders Quiz 1 grading underway Next Quiz, next week.
Coding Concepts (Basics)
CISC101 Reminders All assignments are now posted.
Flowcharts and Pseudo Code
Python I/O Peter Wad Sackett.
Introduction to Computer Science
CISC101 Reminders Quiz 1 marking underway.
Simple Branches and Loops
Another Example Problem
If-Statements and If/Else Statements
Topics Introduction to File Input and Output
Introduction to Computer Science
Presentation transcript:

Python Simple file reading Peter Wad Sackett

Simple Pythonic file reading Using the with statement Python has a special construct for reading files in a simple manner. with open(’filename.txt’, ’r’) as infile: for line in infile: # do something with the line, ok print it print(line) # more python stuff can be done here with the line print(”Now done with the file”) open opens the file ’filename.txt’ for reading; ’r’. The associated filehandle is here called infile, but can be anything. The for loop iterates through each line in the file. The variable is called line (appropiate), but can be anything. When done with the with statement, the file is automatically closed.

Reading a file is like eating a package of chewing gum Open the package Take a piece of gum Chew it well Spit it out Dispose of empty pack Open the file Read a line Compute on the line Done with line Close the file Until empty Until empty Don’t ever put the gum back in your mouth

Questions to ask (yourself) when working with files Did I read any numbers/lines/data in my file? What happens if the input is different from the expected? Can I make input that will break my program?

Objects 101 Every variable, file handle or still untaught ”thing” is an object in Python. Perhaps it is easier to say that everything but keywords like for, while, if, else, and, or, etc. are objects. Any object resides somewhere in memory. An object can hold a value as we see it with variables. On most objects we can perform methods, which are quite similar to functions. These methods transform the object in some way or return a transformed value from the object. myStr = ’I am a string, banzai’ A string variable myStr is an object in memory, myStr is simply the name we use to refer to that object. Making a new variable newStr and assigning myStr to it does not make a new object. It makes a new name for the same object. newStr = myStr

Equality versus identity Given 3 variables and 2 strings like this: myStr = ’I am a string, banzai’ sameStr = ’I am a string,’ + ’ banzai’ newStr = myStr myStr and sameStr are names for two different objects with the same value. They are equal. == is the test for equality. myStr and newStr are names for the same object. They are identical. is is the test for identity. is not is the test for non-identity. if myStr == sameStr: # This is true if myStr == newStr: # This is true if sameStr == newStr: # This is true if myStr is sameStr: # This is false if myStr is newStr: # This is true if sameStr is newStr: # This is false When a later assignment to myStr changes the value of the string, then due to strings being immutable, then the name myStr will be assigned to a new object (string). The newStr will still refer to the old object and keep the value ’I am a string, banzai’.

Some built-in unique objects The values/objects True and False are built-in reserved keywords, like if, etc. There is only one of these objects in Python3. The purpose of True and False is straight-forward and intuitive. var1 = (2 == 2) # this evaluates to true var2 = True # this evaluates to true if var1 is True: # this test is true if var1 is var2: # this test is true # Similar with False There is also None, the no-value, which is different from 0. This is the ”value” you give to a variable when you don’t want to give it a value, because any value would be inappropiate. None is used many places in more advanced Python. Any comparison with True, False, None should be an identity test. High level example: You look for something. You don’t know if you will find it. If you find it, you don’t know what form/value it will have. What should you initially assign to variable that should hold what you are looking for? None, because anything else might be what you are searching for and you won’t know the difference after the search.

Examples Find and print the last line in a file, however the file may be empty. How to handle this gracefully? lastLine = None with open(’filename.txt’, ’r’) as infile: for line in infile: lastLine = line if lastLine is None: print(”Warning: There are no lines in the file”) else: print(lastLine, end=””) Below is a weaker way with the same result. The difference is that we do not programatically know if the file was empty or not. lastLine = ”Warning: There are no lines in the file\n”

Loop control When inside a loop you can exit it early with break. for i in range(10): if i == 5: break print(i) You can also go to the next iteration of the loop with continue. continue This works with both while and for loops and you can have any number of break’s and continue’s in the loop. Generelly, break and continue should not be overused, as they lead to weaker logical thinking. Something beginners are especially prone to do. Yes, that means you.

Not using break 1 Whenever you are using a for loop, you can only terminate the loop early with a break. for i in range(10): if i == 5: break print(i) Solution: Change the for to while and add the break condition to the while’s condition (using the negated form). i = 0 while i < 10 and i != 5: i += 1 The condition in the while clearly states when the loop iterates, and hence when it stops.

Not using break 2 This looping construct can be useful, but rarely is. while True: if some_condition: break if other_condition: # More code Structured alternative: Put the break conditions into the while’s condition, perhaps modifying them slightly apart from negating them. while not some_condition and not other_condition: The condition in the while again clearly states when the loop iterates, and when it stops.

Empty statement At any point where you can write a python statement, you can always use the empty statement: pass pass if var1 == var2: This statement does nothing and takes no time to execute. When the python syntax requires a statement and you don’t wish to ”do” anything, then you pass. When is this used? If you are making some code and you have an if statement you want write, but not just yet, you can pass to remember it. A better use will come later when learning about exceptions.