SlideShare a Scribd company logo
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
• The open() command returns a file object.
<filehandle> = open(<filename>, <access type>)
• 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!”
>>> myFile = open("hello.txt", "r")
Reading the whole file
• You can read the contents of the file into a
single string.
>>> myString = myFile.read()
>>> print myString
Hello, world!
>>> Why is there a
blank line here?
Reading the whole file
• Now add a second line to your file (“How ya
doin’?”) 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'?
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.
>>> myFile = open("hello.txt", "r")
>>> myString = myFile.readline()
>>> print myString
Hello, world!
>>> myString = myFile.readline()
>>> print myString
How ya doin'?
>>>
Writing to a file
• Open the file for writing or appending.
>>> myFile = open("new.txt", "w")
• Use the <file>.write() method.
>>> myFile.write("This is a new filen")
>>> myFile.close()
>>> ^D
> cat new.txt
This is a new file
Always close a file after you
are finished reading from or
writing to it.
Print vs write
• <file>.write() does not automatically
append an end-of-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
if-then-else
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 (<test evaluates to true>):
<execute this block of code>
• 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.
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!
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 "<stdin>", line 4
print "All right by me!"
^
SyntaxError: invalid syntax
Comparison operators
• Boolean: and, or, not
• Numeric: < , > , ==, !=, <>, >=,
<=
• String: in
Examples
seq = 'CAGGT'
>>> if ('C' == seq[0]):
... print 'C is first'
...
C is first
>>> if ('CA' in seq):
... print 'CA in', seq
...
CA in CAGGT
>>> if (('CA' in seq) and ('CG' in seq)):
... print "Both there!"
...
>>>
Beware!
= versus ==
• Single equal assigns a variable
name.
>>> myString == "foo"
Traceback (most recent
call last):
File "<stdin>", line 1,
in ?
NameError: name
'myString' is not
defined
>>> myString = "foo"
>>> myString == "foo"
True
• Double equal tests for equality.
>>> if (myString = "foo"):
File "<stdin>", line 1
if (myString = "foo"):
^
SyntaxError: invalid syntax
>>> if (myString == "foo"):
... print "Yes!"
...
Yes!
if-else statements
if <test1>:
<statement>
else:
<statement>
• The else block executes only if <test1> is false.
>>> if (seq.startswith('T')):
... print 'T start'
... else:
... print 'starts with', seq[0]
...
starts with C
>>>
Evaluates to
FALSE: no print.
if-elif-else
if <test1>:
<statement>
elif <test2>:
<statement>
else:
<statement>
• elif block executes if <test1> is false and
then performs a second <test2>
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
• <file> = open(<filename>, r|w|a>
• <string> = <file>.read()
• <string> = <file>.readline()
• <string list> = <file>.readlines()
• <file>.write(<string>)
• <file>.close()
if <test1>:
<statement>
elif <test2>:
<statement>
else:
<statement>
• Boolean: and, or,
not
• Numeric: < , > , ==,
!=, <>, >=, <=
• String: in, not in
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.
> python read-first-line.py hello.txt
Hello, world!
>
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 carriage return.
> python read-first-line.py hello.txt
Hello, world!
>
Solution #2
import sys
filename = sys.argv[1]
myFile = open(filename, "r")
firstLine = myFile.readline()
firstLine = firstLine[:-1]
myFile.close()
print firstLine
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.
> add-two-numbers.py nine.txt four.txt
9 + 4 = 13
>
Solution #3
import sys
fileOne = open(sys.argv[1], "r")
valueOne = int(fileOne.readline())
fileTwo = open(sys.argv[2], "r")
valueTwo = int(fileTwo.readline())
print valueOne, "+", valueTwo, "=", valueOne + valueTwo
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 it’s not there.
> python find-base.py A GTAGCTA
A occurs at position 3
> 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.
Solution #4
import sys
base = sys.argv[1]
sequence = sys.argv[2]
position = sequence.find(base)
if (position == -1):
print base, "does not occur at all"
else:
print base, "occurs at position", position
Reading
• Chapter 13 of
Learning Python (3rd
edition) by Lutz.

More Related Content

What's hot

Biopython
BiopythonBiopython
Biopython
Karin Lagesen
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
Fariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
Ravi Kiran Khareedi
 
Python tutorial
Python tutorialPython tutorial
Python tutorialRajiv Risi
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
GDSCKYAMBOGO
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
Fariz Darari
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
Priyanka Pradhan
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
Ghadeer AlHasan
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Python
PythonPython
Python
대갑 김
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Python
PythonPython
python codes
python codespython codes
python codes
tusharpanda88
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
Rohan Gupta
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 

What's hot (20)

Biopython
BiopythonBiopython
Biopython
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python
PythonPython
Python
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Python
PythonPython
Python
 
python codes
python codespython codes
python codes
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 
Python course
Python coursePython course
Python course
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 

Similar to 4 b file-io-if-then-else

Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
José Héctor Gálvez
 
PYTHON
PYTHONPYTHON
PYTHON
JOHNYAMSON
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
YashAgarwal413109
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Python File functions
Python File functionsPython File functions
Python File functions
keerthanakommera1
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
Vinod Srivastava
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
arivukarasi2
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Syed Zaid Irshad
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
ssuser92d141
 
1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt
AmritMarwaha1
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
ALOK52916
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
VishwasKumar58
 
Python Basics
Python BasicsPython Basics
Python Basics
MobeenAhmed25
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
RajPurohit33
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
RalAnteloJurado
 
Learn Python in Three Hours - Presentation
Learn Python in Three Hours - PresentationLearn Python in Three Hours - Presentation
Learn Python in Three Hours - Presentation
Naseer-ul-Hassan Rehman
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
kashifmajeedjanjua
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
GeorgePama1
 

Similar to 4 b file-io-if-then-else (20)

Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
PYTHON
PYTHONPYTHON
PYTHON
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Python File functions
Python File functionsPython File functions
Python File functions
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Python Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-FinallyPython Exception handling using Try-Except-Finally
Python Exception handling using Try-Except-Finally
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
Learn Python in Three Hours - Presentation
Learn Python in Three Hours - PresentationLearn Python in Three Hours - Presentation
Learn Python in Three Hours - Presentation
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 

Recently uploaded

WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 

Recently uploaded (20)

WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 

4 b file-io-if-then-else

  • 1. File input and output if-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. <filehandle> = open(<filename>, <access type>) • 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!” >>> myFile = open("hello.txt", "r")
  • 4. Reading the whole file • You can read the contents of the file into a single string. >>> myString = myFile.read() >>> print myString Hello, world! >>> 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. >>> myFile = open("hello.txt", "r") >>> myString = myFile.read() >>> print myString Hello, world! How ya doin'? >>>
  • 6. 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'?
  • 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. >>> myFile = open("hello.txt", "r") >>> myString = myFile.readline() >>> print myString Hello, world! >>> myString = myFile.readline() >>> print myString How ya doin'? >>>
  • 8. Writing to a file • Open the file for writing or appending. >>> myFile = open("new.txt", "w") • Use the <file>.write() method. >>> myFile.write("This is a new filen") >>> myFile.close() >>> ^D > 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 • <file>.write() does not automatically append an end-of-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
  • 11. 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 (<test evaluates to true>): <execute this block of code> • 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. >>> if (seq.startswith("C")): ... print "Starts with C" File "<stdin>", 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. >>> 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 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 "<stdin>", line 4 print "All right by me!" ^ SyntaxError: invalid syntax
  • 15. Comparison operators • Boolean: and, or, not • Numeric: < , > , ==, !=, <>, >=, <= • String: in
  • 16. Examples seq = 'CAGGT' >>> if ('C' == seq[0]): ... print 'C is first' ... C is first >>> if ('CA' in seq): ... print 'CA in', seq ... CA in CAGGT >>> if (('CA' in seq) and ('CG' in seq)): ... print "Both there!" ... >>>
  • 17. Beware! = versus == • Single equal assigns a variable name. >>> myString == "foo" Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'myString' is not defined >>> myString = "foo" >>> myString == "foo" True • Double equal tests for equality. >>> if (myString = "foo"): File "<stdin>", line 1 if (myString = "foo"): ^ SyntaxError: invalid syntax >>> if (myString == "foo"): ... print "Yes!" ... Yes!
  • 18. if-else statements if <test1>: <statement> else: <statement> • The else block executes only if <test1> is false. >>> if (seq.startswith('T')): ... print 'T start' ... else: ... print 'starts with', seq[0] ... starts with C >>> Evaluates to FALSE: no print.
  • 19. if-elif-else if <test1>: <statement> elif <test2>: <statement> else: <statement> • elif block executes if <test1> is false and then performs a second <test2>
  • 20. 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
  • 21. • <file> = open(<filename>, r|w|a> • <string> = <file>.read() • <string> = <file>.readline() • <string list> = <file>.readlines() • <file>.write(<string>) • <file>.close() if <test1>: <statement> elif <test2>: <statement> else: <statement> • Boolean: and, or, not • Numeric: < , > , ==, !=, <>, >=, <= • 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. > python read-first-line.py hello.txt Hello, world! >
  • 23. Solution #1 import sys filename = sys.argv[1] 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. > python read-first-line.py hello.txt Hello, world! >
  • 25. Solution #2 import sys filename = sys.argv[1] 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. > add-two-numbers.py nine.txt four.txt 9 + 4 = 13 >
  • 27. Solution #3 import sys fileOne = open(sys.argv[1], "r") valueOne = int(fileOne.readline()) fileTwo = open(sys.argv[2], "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 it’s not there. > python find-base.py A GTAGCTA A occurs at position 3 > 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.argv[1] sequence = sys.argv[2] 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.