File input and output if-then-else - PowerPoint PPT Presentation

About This Presentation
Title:

File input and output if-then-else

Description:

File input and output if-then-else Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble File input and output Opening files ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 31
Provided by: williams150
Category:
Tags: command | file | input | lines | output

less

Transcript and Presenter's Notes

Title: File input and output if-then-else


1
File input and outputif-then-else
  • Genome 559 Introduction to Statistical and
    Computational Genomics
  • Prof. William Stafford Noble

2
File input and output
3
Opening files
  • The open() command returns a file object.
  • ltfilehandlegt open(ltfilenamegt, ltaccess typegt)
  • Python can read, write or append to a file
  • 'r' read
  • 'w' write
  • 'a' append
  • Create a file called hello.txt containing one
    line Hello, world!
  • gtgtgt myFile open("hello.txt", "r")

4
Reading the whole file
  • You can read the contents of the file into a
    single string.
  • gtgtgt myString myFile.read()
  • gtgtgt print myString
  • Hello, world!
  • gtgtgt

Why is there a blank line here?
5
Reading the whole file
  • Now add a second line to your file (How ya
    doin?) and try again.
  • gtgtgt myFile open("hello.txt", "r")
  • gtgtgt myString myFile.read()
  • gtgtgt print myString
  • Hello, world!
  • How ya doin'?
  • gtgtgt

6
Reading the whole file
  • Alternatively, you can read the file into a list
    of strings.
  • gtgtgt myFile open("hello.txt", "r")
  • gtgtgt myStringList myFile.readlines()
  • gtgtgt print myStringList
  • 'Hello, world!\n', "How ya doin'?\n"
  • gtgtgt print myStringList1
  • How ya doin'?

7
Reading one line at a time
  • The readlines() command puts all the lines into a
    list of strings.
  • The readline() command returns the next line.
  • gtgtgt myFile open("hello.txt", "r")
  • gtgtgt myString myFile.readline()
  • gtgtgt print myString
  • Hello, world!
  • gtgtgt myString myFile.readline()
  • gtgtgt print myString
  • How ya doin'?
  • gtgtgt

8
Writing to a file
  • Open the file for writing or appending.
  • gtgtgt myFile open("new.txt", "w")
  • Use the ltfilegt.write() method.
  • gtgtgt myFile.write("This is a new file\n")
  • gtgtgt myFile.close()
  • gtgtgt D
  • gt cat new.txt
  • This is a new file

Always close a file after you are finished
reading from or writing to it.
9
Print vs write
  • ltfilegt.write() does not automatically append an
    end-of-line character.
  • ltfilegt.write() requires a string as input
  • gtgtgt newFile.write("foo")
  • gtgtgt newFile.write(1)
  • Traceback (most recent call last)
  • File "ltstdingt", line 1, in ?
  • TypeError argument 1 must be string or read-only
    character buffer, not int

10
if-then-else
11
The if statement
  • gtgtgt if (seq.startswith("C"))
  • ... print "Starts with C"
  • ...
  • Starts with C
  • gtgtgt
  • A block is a group of lines of code that belong
    together.
  • if (lttest evaluates to truegt)
  • ltexecute this block of codegt
  • In the Python interpreter, the ellipse indicates
    that you are inside a block.
  • Python uses indentation to keep track of blocks.
  • You can use any number of spaces to indicate
    blocks, but you must be consistent.
  • An unindented or blank line indicates the end of
    a block.

12
The if statement
  • Try doing an if statement without indentation.
  • gtgtgt if (seq.startswith("C"))
  • ... print "Starts with C"
  • File "ltstdingt", line 2
  • print "Starts with C"
  • IndentationError expected an indented block

13
Multiline blocks
  • Try doing an if statement with multiple lines in
    the block.
  • gtgtgt if (seq.startswith("C"))
  • ... print "Starts with C"
  • ... print "All right by me!"
  • ...
  • Starts with C
  • All right by me!

14
Multiline blocks
  • What happens if you dont use the same number of
    spaces to indent the block?
  • gtgtgt if (seq.startswith("C"))
  • ... print "Starts with C"
  • ... print "All right by me!"
  • File "ltstdingt", line 4
  • print "All right by me!"
  • SyntaxError invalid syntax

15
Comparison operators
  • Boolean and, or, not
  • Numeric lt , gt , , !, ltgt, gt, lt
  • String in

16
Examples
  • seq 'CAGGT'
  • gtgtgt if ('C' seq0)
  • ... print 'C is first'
  • ...
  • C is first
  • gtgtgt if ('CA' in seq)
  • ... print 'CA in', seq
  • ...
  • CA in CAGGT
  • gtgtgt if (('CA' in seq) and ('CG' in seq))
  • ... print "Both there!"
  • ...
  • gtgtgt

17
Beware! versus
  • Single equal assigns a variable name.
  • gtgtgt myString "foo"
  • Traceback (most recent call last)
  • File "ltstdingt", line 1, in ?
  • NameError name 'myString' is not defined
  • gtgtgt myString "foo"
  • gtgtgt myString "foo"
  • True
  • Double equal tests for equality.
  • gtgtgt if (myString "foo")
  • File "ltstdingt", line 1
  • if (myString "foo")
  • SyntaxError invalid syntax
  • gtgtgt if (myString "foo")
  • ... print "Yes!"
  • ...
  • Yes!

18
if-else statements
  • if lttest1gt
  • ltstatementgt
  • else
  • ltstatementgt
  • The else block executes only if lttest1gt is false.
  • gtgtgt if (seq.startswith('T'))
  • ... print 'T start'
  • ... else
  • ... print 'starts with', seq0
  • ...
  • starts with C
  • gtgtgt

Evaluates to FALSE no print.
19
if-elif-else
  • if lttest1gt
  • ltstatementgt
  • elif lttest2gt
  • ltstatementgt
  • else
  • ltstatementgt
  • elif block executes if lttest1gt is false and then
    performs a second lttest2gt

20
Example
  • gtgtgt base 'C'
  • gtgtgt 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

21
  • ltfilegt open(ltfilenamegt, rwagt
  • ltstringgt ltfilegt.read()
  • ltstringgt ltfilegt.readline()
  • ltstring listgt ltfilegt.readlines()
  • ltfilegt.write(ltstringgt)
  • ltfilegt.close()
  • if lttest1gt
  • ltstatementgt
  • elif lttest2gt
  • ltstatementgt
  • else
  • ltstatementgt
  • Boolean and, or, not
  • Numeric lt , gt , , !, ltgt, gt, lt
  • String in, not in

22
Sample problem 1
  • Write a program read-first-line.py that takes a
    file name from the command line, opens the file,
    reads the first line, and prints the result to
    the screen.
  • gt python read-first-line.py hello.txt
  • Hello, world!
  • gt

23
Solution 1
  • import sys
  • filename sys.argv1
  • myFile open(filename, "r")
  • firstLine myFile.readline()
  • myFile.close()
  • print firstLine

24
Sample problem 2
  • Modify your program to print the first line
    without an extra carriage return.
  • gt python read-first-line.py hello.txt
  • Hello, world!
  • gt

25
Solution 2
  • import sys
  • filename sys.argv1
  • myFile open(filename, "r")
  • firstLine myFile.readline()
  • firstLine firstLine-1
  • myFile.close()
  • print firstLine

26
Sample problem 3
  • Write a program add-two-numbers.py that reads one
    integer from the first line of one file and a
    second integer from the first line of a second
    file and then prints their sum.
  • gt add-two-numbers.py nine.txt four.txt
  • 9 4 13
  • gt

27
Solution 3
  • import sys
  • fileOne open(sys.argv1, "r")
  • valueOne int(fileOne.readline())
  • fileTwo open(sys.argv2, "r")
  • valueTwo int(fileTwo.readline())
  • print valueOne, "", valueTwo, "", valueOne
    valueTwo

28
Sample problem 4
  • 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 its
    not there.
  • gt python find-base.py A GTAGCTA
  • A occurs at position 3
  • gt python find-base.py A GTGCT
  • A does not occur at all

Hint S.find('G') returns -1 if it can't find
the requested sequence.
29
Solution 4
  • import sys
  • base sys.argv1
  • sequence sys.argv2
  • position sequence.find(base)
  • if (position -1)
  • print base, "does not occur at all"
  • else
  • print base, "occurs at position", position

30
Reading
  • Chapter 13 of Learning Python (3rd edition) by
    Lutz.
Write a Comment
User Comments (0)
About PowerShow.com