Docsity

Python File Input and Output with if-then-else Statements, Slides of Genomics

Partial preview of the text

Download Python File Input and Output with if-then-else Statements and more Slides Genomics in PDF only on Docsity!

File input and output

if-then-else

Genome 559: Introduction to

Statistical and Computational Genomics

Prof. James H. Thomas

Opening files

  • The open() command returns a file object: <file_object> = open(, )
  • Python will read, write or append to a file according to the access type requested: - 'r' = read - 'w' = write - 'a' = append
  • Open for reading a file called “hello.txt”:

myFile = open("hello.txt", "r")

Reading the whole file

  • Now add a second line to your file (“How ya

doin’?\n”) and try again.

myFile = open("hello.txt", "r")

myString = myFile.read()

print myString

Hello, world!

How ya doin'?

Reading the whole file

  • Alternatively, you can read the file into a list

of strings:

myFile = open("hello.txt", "r")

myStringList = myFile.readlines()

print myStringList

['Hello, world!\n', ‘How ya doin'?\ n’]

print myStringList[1]

How ya doin'?

this file method returns a list of strings

Writing to a file

  • Open the file for writing or appending:

myFile = open("new.txt", "w")

  • Use the .write() method:

myFile.write("This is a new file\n")

myFile.close()

Ctl-D (exit the python interpreter)

cat new.txt

This is a new file (^) always close a file after you are finished reading from or writing to it.

.write() is a little different from print()

  • .write() does not automatically

append a new-line character.

  • .write() requires a string as input.

newFile.write("foo") newFile.write(1) Traceback (most recent call last): File "", line 1, in? TypeError: argument 1 must be string or read-only

character buffer, not int

(also of course print() goes to the screen and .write() goes to a file)

The if statement

if (seq.startswith("C")): ... print "Starts with C" ... Starts with C

  • A block is a group of lines of code that belong together.

if ():

  • In the Python interpreter, the ellipse 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 blocks, but you must be consistent. Using 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 "", line 2 print "Starts with C" ^

IndentationError: expected an indented block

Multiline blocks

  • What happens if you don’t use the same number of spaces to indent the block?

if (seq.startswith("C")): ... print "Starts with C" ... print "All right by me!" File "", line 4 print "All right by me!" ^ SyntaxError: invalid syntax

This is why I prefer to use the character – it is always exactly correct.

Comparison operators

  • Boolean: and, or, not
  • Numeric: < , > , ==, !=, >=, <=
  • String: in, not in

< is less than

is greater than == is equal to != is NOT equal to <= is less than or equal to = is greater than or equal to

Beware!

= versus ==

  • Single equal assigns a variable name.
  • Double equal tests for equality.

Combining tests

x = 1 y = 2 z = 3 if ((x < y) and (y != z)): do something if ((x > y) or (y == z)): do something else

Evaluation starts with the innermost parentheses and works out

if (((x <= y) and (x < z)) or ((x == y) and not (x == z)))

if-elif-else

if :

elif :

else:

  • elif block executes if is false and

then performs a second

  • Only one of the blocks is ever executed.

Can be read this way:

if test1 is true then run block1, else if test2 is true run block2, else run block

Example

base = 'C' if (base == 'A'): ... print "adenine" ... elif (base == 'C'): ... print "cytosine" ... elif (base == 'G'): ... print "guanine" ... elif (base == 'T'): ... print "thymine" ... else: ... print "Invalid base!“ ... cytosine