SlideShare a Scribd company logo
files!
(and reading and writing to them)
The plan!
Basics: data types (and operations & calculations)
Basics: conditionals & iteration
Basics: lists, tuples, dictionaries
Basics: writing functions
Reading & writing files: opening, parsing & formats
Working with numbers: numpy & scipy
Making plots: matplotlib & pylab
… if you guys want more after all of that …
Writing better code: functions, pep8, classes
Working with numbers: Numpy & Scipy (advanced)
Other modules: Pandas & Scikit-learn
Interactive notebooks: ipython & jupyter
Advanced topics: virtual environments & version control
reading from a file
---- smallfile.txt ----
apple
dog
hammock
reading from a file
# lets open and read a small file
file_handle = open("smallfile.txt", "rU")
content = file_handle.read()
print content
# close the file :)
file_handle.close()
---- smallfile.txt ----
apple
dog
hammock
reading a file
handle = open("filename", "rU")
do stuff
handle.close()
reading from a file
# lets open and read a small file
file_handle = open("smallfile.txt", "rU")
content = file_handle.read()
print content
# close the file :)
file_handle.close()
# we can only do this once after opening a file
file_handle = open("smallfile.txt", "rU")
content = file_handle.read()
print content
content = file_handle.read()
print content
# close the file :)
file_handle.close()
---- smallfile.txt ----
apple
dog
hammock
reading a file
handle = open("filename", "rU")
do stuff
handle.close()
reading from a file
# lets read it line by line
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
print "Line:", line
# close the file :)
file_handle.close()
# them hidden newline characters...
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
print len(line)
# close the file :)
file_handle.close()
Reading a file, line by line
handle = open("filename", "rU")
for line in handle:
do stuff
handle.close()
reading from a file
# lets read it line by line
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
print "Line:", line
# close the file :)
file_handle.close()
Reading a file, line by line
handle = open("filename", "rU")
for line in handle:
do stuff
handle.close()
reading from a file
# lets read it line by line
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
print "Line:", line
# close the file :)
file_handle.close()
# them hidden newline characters...
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
print len(line)
# close the file :)
file_handle.close()
---- smallfile.txt ----
applen
dogn
hammockn
Reading a file, line by line
handle = open("filename", "rU")
for line in handle:
do stuff
handle.close()
reading from a file
# lets read it line by line
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
print "Line:", line
# close the file :)
file_handle.close()
# them hidden newline characters...
file_handle = open("smallfile.txt", "rU")
for line in file_handle:
line_cleaned = line.strip()
print line
# close the file :)
file_handle.close()
---- smallfile.txt ----
applen
dogn
hammockn
Reading a file, line by line
handle = open("filename", "rU")
for line in handle:
line_cleaned = line.strip()
do stuff
handle.close()
writing to a file
# lets read it line by line
file_handle = open("myfile.txt", "w")
file_handle.write("My name is Marc")
# close the file :)
file_handle.close()
# we can keep on writing to the file while its open
file_handle = open("myfile.txt", "w")
file_handle.write("My name is Marc.")
file_handle.write("It's a fine day.")
file_handle.write("People open windows..")
# close the file :)
file_handle.close()
removing the "n"
handle = open("filename", "w")
handle.write(some_string)
handle.close()
writing to a file
# lets read it line by line
file_handle = open("myfile.txt", "w")
file_handle.write("My name is Marc")
# close the file :)
file_handle.close()
# we can keep on writing to the file while its open
file_handle = open("myfile.txt", "w")
file_handle.write("My name is Marc.n")
file_handle.write("It's a fine day.n")
file_handle.write("People open windows.n")
# close the file :)
file_handle.close()
removing the "n"
handle = open("filename", "w")
handle.write(some_string)
handle.close()
writing to a file
# lets read it line by line
file_handle = open("myfile.txt", "w")
file_handle.write("My name is Marc")
# close the file :)
file_handle.close()
# we can keep on writing to the file while its open
file_handle = open("myfile.txt", "w")
file_handle.write("My name is Marc.n")
file_handle.write("It's a fine day.n")
file_handle.write("People open windows.n")
# close the file :)
file_handle.close()
# lastly, we can ONLY write strings:
file_handle = open("myfile.txt", "w")
file_handle.write(10000) # will not work
file_handle.write("10000" + "n") # is better
# close the file :)
file_handle.close()
removing the "n"
handle = open("filename", "w")
handle.write(some_string)
handle.close()
exercises!
- Write function that takes three inputs (numbers x, y and z), and produces the
result of : a + b - c. Use return to be able to store and use the value later.
version 2: as above, but if no numbers for b or c are specified, use 5 and 10 as default
values.
---- testfile.txt ----
apple
dog
hammock
exercises!
words.txt
- Get the file “words.txt”.
- How many words are there in the file?
- How often does the word “megacycle” occur?
numbers.txt
- Get the file “numbers.txt”.
- How many numbers are there in the file?
- What is the sum of all of the numbers?
mydata.txt
- Create a program that asks a user for the a)
Name, b) favourite color and c) the average
flight speed of a swallow, and saves these to a
text file (see exaple).
---- output.txt ----
Name: Marc
Favourite Color: Orange
Average speed of swallow: 12

More Related Content

What's hot

file
filefile
file
teach4uin
 
PHP file handling
PHP file handling PHP file handling
PHP file handling
wahidullah mudaser
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operationsmussawir20
 
R- create a table from a list of files.... before webmining
R- create a table from a list of files.... before webminingR- create a table from a list of files.... before webmining
R- create a table from a list of files.... before webmining
Gabriela Plantie
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
Basic command ppt
Basic command pptBasic command ppt
Basic command pptRohit Kumar
 
File handling in c
File handling in c File handling in c
File handling in c
Vikash Dhal
 
Python 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation CheatsheetPython 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation Cheatsheet
Isham Rashik
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
Files in c++
Files in c++Files in c++
Files in c++
NivethaJeyaraman
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
Khushal Mehta
 
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
Younggun Kim
 
php file uploading
php file uploadingphp file uploading
php file uploading
Purushottam Kumar
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
Ananda Kumar HN
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
AbdulghafarStanikzai
 

What's hot (19)

file
filefile
file
 
PHP file handling
PHP file handling PHP file handling
PHP file handling
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
R- create a table from a list of files.... before webmining
R- create a table from a list of files.... before webminingR- create a table from a list of files.... before webmining
R- create a table from a list of files.... before webmining
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling in c
File handling in cFile handling in c
File handling in c
 
working with files
working with filesworking with files
working with files
 
Basic command ppt
Basic command pptBasic command ppt
Basic command ppt
 
File handling
File handlingFile handling
File handling
 
File handling in c
File handling in c File handling in c
File handling in c
 
Python 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation CheatsheetPython 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation Cheatsheet
 
Files in php
Files in phpFiles in php
Files in php
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
 
php file uploading
php file uploadingphp file uploading
php file uploading
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 

Similar to Class 7b: Files & File I/O

Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
Vishal Dutt
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
RonitVaskar2
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
Inzamam Baig
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
File handling in Python
File handling in PythonFile handling in Python
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
10 Python file.pptx
10 Python file.pptx10 Python file.pptx
10 Python file.pptx
SUJALORAON
 
Python File functions
Python File functionsPython File functions
Python File functions
keerthanakommera1
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Workshop programs
Workshop programsWorkshop programs
Workshop programs
Kracekumar Ramaraju
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 

Similar to Class 7b: Files & File I/O (20)

Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Python-files
Python-filesPython-files
Python-files
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
10 Python file.pptx
10 Python file.pptx10 Python file.pptx
10 Python file.pptx
 
Python File functions
Python File functionsPython File functions
Python File functions
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Workshop programs
Workshop programsWorkshop programs
Workshop programs
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 

More from Marc Gouw

Class 2: Welcome part 2
Class 2: Welcome part 2Class 2: Welcome part 2
Class 2: Welcome part 2
Marc Gouw
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
Marc Gouw
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
Marc Gouw
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
Marc Gouw
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
Marc Gouw
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
Marc Gouw
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
Marc Gouw
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
Marc Gouw
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
Marc Gouw
 

More from Marc Gouw (9)

Class 2: Welcome part 2
Class 2: Welcome part 2Class 2: Welcome part 2
Class 2: Welcome part 2
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
 

Recently uploaded

general properties of oerganologametal.ppt
general properties of oerganologametal.pptgeneral properties of oerganologametal.ppt
general properties of oerganologametal.ppt
IqrimaNabilatulhusni
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
muralinath2
 
nodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptxnodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptx
alishadewangan1
 
What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.
moosaasad1975
 
in vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptxin vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptx
yusufzako14
 
bordetella pertussis.................................ppt
bordetella pertussis.................................pptbordetella pertussis.................................ppt
bordetella pertussis.................................ppt
kejapriya1
 
S.1 chemistry scheme term 2 for ordinary level
S.1 chemistry scheme term 2 for ordinary levelS.1 chemistry scheme term 2 for ordinary level
S.1 chemistry scheme term 2 for ordinary level
ronaldlakony0
 
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATIONPRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
ChetanK57
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
silvermistyshot
 
Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...
Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...
Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...
Ana Luísa Pinho
 
GBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram StainingGBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram Staining
Areesha Ahmad
 
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
yqqaatn0
 
Toxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and ArsenicToxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and Arsenic
sanjana502982
 
如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样
如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样
如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样
yqqaatn0
 
Seminar of U.V. Spectroscopy by SAMIR PANDA
 Seminar of U.V. Spectroscopy by SAMIR PANDA Seminar of U.V. Spectroscopy by SAMIR PANDA
Seminar of U.V. Spectroscopy by SAMIR PANDA
SAMIR PANDA
 
Introduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptxIntroduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptx
zeex60
 
role of pramana in research.pptx in science
role of pramana in research.pptx in sciencerole of pramana in research.pptx in science
role of pramana in research.pptx in science
sonaliswain16
 
Mudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdf
Mudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdfMudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdf
Mudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdf
frank0071
 
Phenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvementPhenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvement
IshaGoswami9
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Sérgio Sacani
 

Recently uploaded (20)

general properties of oerganologametal.ppt
general properties of oerganologametal.pptgeneral properties of oerganologametal.ppt
general properties of oerganologametal.ppt
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
 
nodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptxnodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptx
 
What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.
 
in vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptxin vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptx
 
bordetella pertussis.................................ppt
bordetella pertussis.................................pptbordetella pertussis.................................ppt
bordetella pertussis.................................ppt
 
S.1 chemistry scheme term 2 for ordinary level
S.1 chemistry scheme term 2 for ordinary levelS.1 chemistry scheme term 2 for ordinary level
S.1 chemistry scheme term 2 for ordinary level
 
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATIONPRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
PRESENTATION ABOUT PRINCIPLE OF COSMATIC EVALUATION
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
 
Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...
Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...
Deep Behavioral Phenotyping in Systems Neuroscience for Functional Atlasing a...
 
GBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram StainingGBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram Staining
 
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
 
Toxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and ArsenicToxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and Arsenic
 
如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样
如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样
如何办理(uvic毕业证书)维多利亚大学毕业证本科学位证书原版一模一样
 
Seminar of U.V. Spectroscopy by SAMIR PANDA
 Seminar of U.V. Spectroscopy by SAMIR PANDA Seminar of U.V. Spectroscopy by SAMIR PANDA
Seminar of U.V. Spectroscopy by SAMIR PANDA
 
Introduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptxIntroduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptx
 
role of pramana in research.pptx in science
role of pramana in research.pptx in sciencerole of pramana in research.pptx in science
role of pramana in research.pptx in science
 
Mudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdf
Mudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdfMudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdf
Mudde & Rovira Kaltwasser. - Populism - a very short introduction [2017].pdf
 
Phenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvementPhenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvement
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
 

Class 7b: Files & File I/O

  • 1. files! (and reading and writing to them)
  • 2. The plan! Basics: data types (and operations & calculations) Basics: conditionals & iteration Basics: lists, tuples, dictionaries Basics: writing functions Reading & writing files: opening, parsing & formats Working with numbers: numpy & scipy Making plots: matplotlib & pylab … if you guys want more after all of that … Writing better code: functions, pep8, classes Working with numbers: Numpy & Scipy (advanced) Other modules: Pandas & Scikit-learn Interactive notebooks: ipython & jupyter Advanced topics: virtual environments & version control
  • 3. reading from a file ---- smallfile.txt ---- apple dog hammock
  • 4. reading from a file # lets open and read a small file file_handle = open("smallfile.txt", "rU") content = file_handle.read() print content # close the file :) file_handle.close() ---- smallfile.txt ---- apple dog hammock reading a file handle = open("filename", "rU") do stuff handle.close()
  • 5. reading from a file # lets open and read a small file file_handle = open("smallfile.txt", "rU") content = file_handle.read() print content # close the file :) file_handle.close() # we can only do this once after opening a file file_handle = open("smallfile.txt", "rU") content = file_handle.read() print content content = file_handle.read() print content # close the file :) file_handle.close() ---- smallfile.txt ---- apple dog hammock reading a file handle = open("filename", "rU") do stuff handle.close()
  • 6. reading from a file # lets read it line by line file_handle = open("smallfile.txt", "rU") for line in file_handle: print "Line:", line # close the file :) file_handle.close() # them hidden newline characters... file_handle = open("smallfile.txt", "rU") for line in file_handle: print len(line) # close the file :) file_handle.close() Reading a file, line by line handle = open("filename", "rU") for line in handle: do stuff handle.close()
  • 7. reading from a file # lets read it line by line file_handle = open("smallfile.txt", "rU") for line in file_handle: print "Line:", line # close the file :) file_handle.close() Reading a file, line by line handle = open("filename", "rU") for line in handle: do stuff handle.close()
  • 8. reading from a file # lets read it line by line file_handle = open("smallfile.txt", "rU") for line in file_handle: print "Line:", line # close the file :) file_handle.close() # them hidden newline characters... file_handle = open("smallfile.txt", "rU") for line in file_handle: print len(line) # close the file :) file_handle.close() ---- smallfile.txt ---- applen dogn hammockn Reading a file, line by line handle = open("filename", "rU") for line in handle: do stuff handle.close()
  • 9. reading from a file # lets read it line by line file_handle = open("smallfile.txt", "rU") for line in file_handle: print "Line:", line # close the file :) file_handle.close() # them hidden newline characters... file_handle = open("smallfile.txt", "rU") for line in file_handle: line_cleaned = line.strip() print line # close the file :) file_handle.close() ---- smallfile.txt ---- applen dogn hammockn Reading a file, line by line handle = open("filename", "rU") for line in handle: line_cleaned = line.strip() do stuff handle.close()
  • 10. writing to a file # lets read it line by line file_handle = open("myfile.txt", "w") file_handle.write("My name is Marc") # close the file :) file_handle.close() # we can keep on writing to the file while its open file_handle = open("myfile.txt", "w") file_handle.write("My name is Marc.") file_handle.write("It's a fine day.") file_handle.write("People open windows..") # close the file :) file_handle.close() removing the "n" handle = open("filename", "w") handle.write(some_string) handle.close()
  • 11. writing to a file # lets read it line by line file_handle = open("myfile.txt", "w") file_handle.write("My name is Marc") # close the file :) file_handle.close() # we can keep on writing to the file while its open file_handle = open("myfile.txt", "w") file_handle.write("My name is Marc.n") file_handle.write("It's a fine day.n") file_handle.write("People open windows.n") # close the file :) file_handle.close() removing the "n" handle = open("filename", "w") handle.write(some_string) handle.close()
  • 12. writing to a file # lets read it line by line file_handle = open("myfile.txt", "w") file_handle.write("My name is Marc") # close the file :) file_handle.close() # we can keep on writing to the file while its open file_handle = open("myfile.txt", "w") file_handle.write("My name is Marc.n") file_handle.write("It's a fine day.n") file_handle.write("People open windows.n") # close the file :) file_handle.close() # lastly, we can ONLY write strings: file_handle = open("myfile.txt", "w") file_handle.write(10000) # will not work file_handle.write("10000" + "n") # is better # close the file :) file_handle.close() removing the "n" handle = open("filename", "w") handle.write(some_string) handle.close()
  • 13. exercises! - Write function that takes three inputs (numbers x, y and z), and produces the result of : a + b - c. Use return to be able to store and use the value later. version 2: as above, but if no numbers for b or c are specified, use 5 and 10 as default values. ---- testfile.txt ---- apple dog hammock
  • 14. exercises! words.txt - Get the file “words.txt”. - How many words are there in the file? - How often does the word “megacycle” occur? numbers.txt - Get the file “numbers.txt”. - How many numbers are there in the file? - What is the sum of all of the numbers? mydata.txt - Create a program that asks a user for the a) Name, b) favourite color and c) the average flight speed of a swallow, and saves these to a text file (see exaple). ---- output.txt ---- Name: Marc Favourite Color: Orange Average speed of swallow: 12