Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Simple file reading

Similar presentations


Presentation on theme: "Python Simple file reading"— Presentation transcript:

1 Python Simple file reading
Peter Wad Sackett

2 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.

3 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

4 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?

5 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

6 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’.

7 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.

8 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”

9 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.

10 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.

11 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.

12 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.


Download ppt "Python Simple file reading"

Similar presentations


Ads by Google