4B File IO Conditionals
4B File IO Conditionals
and conditionals
>>>
Reading the whole file
• Alternatively, you can read the file into a list
of strings:
open("new.txt", "w") will overwrite an existing file (or create a new one)
open("new.txt", "a") will append to an existing file
<file>.write() is a little
different from print()
• <file>.write() does not automatically
append a new-line character.
• <file>.write() requires a string as input.
>>> newFile.write("foo")
>>> newFile.write(1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: argument 1 must be string or read-only
character buffer, not int
>>> newFile.write(str(1)) # str converts to string
(also of course print() goes to the screen and <file>.write() goes to a file)
Conditional code execution
and code blocks
if-elif-else
The if statement
>>> if (seq.startswith("C")):
... print "Starts with C"
...
Starts with C
>>>
• In the Python interpreter, the ellipsis indicates that you are inside
a block (on my Win machine it is just a blank indentation).
• Python uses indentation to keep track of blocks.
• You can use any number of spaces to indicate a block, but you must
be consistent. Using one <tab> is simplest.
• An unindented or blank line indicates the end of a block.
The if statement
• Try doing an if statement without indentation:
>>> if (seq.startswith("C")):
... print "Starts with C"
File "<stdin>", line 2
print "Starts with C"
^
IndentationError: expected an indented block
Multiline blocks
• Try doing an if statement with multiple lines in the
block.
>>> if (seq.startswith("C")):
... print "Starts with C"
... print "All right by me!"
...
Starts with C
All right by me!
>>> if (seq.startswith("C")):
... print "Starts with C"
... print "All right by me!"
File "<stdin>", line 4
print "All right by me!"
^
SyntaxError: invalid syntax
This is why I prefer to use the <tab> character – it is always exactly correct.
Comparison operators used frequently
in conditional statements
>
Solution #1
import sys
filename = sys.argv[1]
myFile = open(filename, "r")
firstLine = myFile.readline()
myFile.close()
print firstLine
Sample problem #2
• Modify your program to print the first
line without an extra new line.
import sys
fileOne = open(sys.argv[1], "r")
valOne = int(fileOne.readline().strip())
fileOne.close()
fileTwo = open(sys.argv[2], "r")
valTwo = int(fileTwo.readline().strip())
fileTwo.close()
if valOne < valTwo:
print valOne, "+", valTwo, "=", valOne + valTwo
else:
print valOne, "*", valTwo, "=", valOne * valTwo
Sample problem #4 (review)
• Write a program find-base.py that takes as input a
DNA sequence and a nucleotide. The program should
print the number of times the nucleotide occurs in
the sequence, or a message saying it’s not there.
Do the same thing but output a list of all the positions where seq2
appears in seq1 (tricky with your current knowledge).