Download Python Simple file reading

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
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:
print(line)
# doing something with the line
# more python stuff can be done here
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.
2
DTU Bioinformatics, Technical University of Denmark
Questions to ask (yourself) when working with files
Questions
Did I read any numbers/lines?
What happens if the input is different from the expected?
Can I make input that will break my program?
3
DTU Bioinformatics, Technical University of Denmark
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
4
DTU Bioinformatics, Technical University of Denmark
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’.
This does not happen when the object is mutable.
5
DTU Bioinformatics, Technical University of Denmark
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)
var2 = True
if var1 is True:
if var1 is var2:
# Similar with False
#
#
#
#
this
this
this
this
evaluates to true
evaluates to true
test is true
test is true
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.
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.
6
DTU Bioinformatics, Technical University of Denmark
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.
for i in range(10):
if i == 5:
continue
print(i)
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.
7
DTU Bioinformatics, Technical University of Denmark
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:
print(i)
i += 1
The condition in the while clearly states when the loop iterates,
and hence when it stops.
8
DTU Bioinformatics, Technical University of Denmark
Not using break 2
This looping construct can be useful, but rarely is.
while True:
if some_condition:
break
if other_condition:
break
# 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:
# More code
The condition in the while again clearly states when the loop
iterates, and when it stops.
9
DTU Bioinformatics, Technical University of Denmark
Empty statement
At any point where you can write a python statement, you can
always use the empty statement: pass
pass
if var1 == var2:
pass
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.
10
DTU Bioinformatics, Technical University of Denmark