SlideShare a Scribd company logo
1 of 87
Download to read offline
Python 
Input and Output 
Copyright © Software Carpentry 2010 
This work is licensed under the Creative Commons Attribution License 
See http://software-carpentry.org/license.html for more information.
Been using print to see what programs are doing 
Python Input and Output
Been using print to see what programs are doing 
How to save data to files? 
Python Input and Output
Been using print to see what programs are doing 
How to save data to files? 
And read ddaattaa ffrroomm tthheemm?? 
Python Input and Output
Been using print to see what programs are doing 
How to save data to files? 
And read ddaattaa ffrroomm tthheemm?? 
Python's solution looks very much like C's 
Python Input and Output
Been using print to see what programs are doing 
How to save data to files? 
And read ddaattaa ffrroomm tthheemm?? 
Python's solution looks very much like C's 
– A file is a sequence of bytes 
Python Input and Output
Been using print to see what programs are doing 
How to save data to files? 
And read ddaattaa ffrroomm tthheemm?? 
Python's solution looks very much like C's 
– A file is a sequence of bytes 
– But it's often more useful to treat it as a sequence 
of lines 
Python Input and Output
Sample data file 
Three things are certain: 
Death, taxes, and lost data. 
Guess wwhhiicchh hhaass ooccccuurrrreedd.. 
Errors have occurred. 
We won't tell you where or why. 
Lazy programmers. 
With searching comes loss 
and the presence of absence: 
"My Thesis" not found. 
A crash reduces 
your expensive computer 
to a simple stone. 
Python Input and Output
How many characters in a file? 
Python Input and Output
How many characters in a file? 
bytes 
Python Input and Output
How many characters in a file? 
bytes Assume 1-to-1 for now 
Python Input and Output
How many characters in a file? 
bytes Assume 1-to-1 for now 
RReevviissiitt llaatteerr 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Create a file object 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
File to connect to 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
To read 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Now holds file object 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Read entire content 
of file into a string 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Now has a copy of 
all the bytes that were 
in the file 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Disconnect from the file 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Disconnect from the file 
Not strictly necessary 
in small programs, but 
good practice 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Report how many 
characters were read 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
Report how many 
characters were read 
bytes 
Python Input and Output
How many characters in a file? 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
print len(data) 
293 
Python Input and Output
If the file might be large, better to read in chunks 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
Read (at wwwwhhhhiiiilllleeee data != '': most) 64 bytes 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
Read (at wwwwhhhhiiiilllleeee data != '': most) 64 bytes 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
Or the empty string 
if there is no more data 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
Keep looping as long as 
the last read returned 
some data 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
Do something with 
the data 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
(Try to) reload 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
Should be 0 (or the loop 
would still be running) 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
64 
64 
64 
64 
37 
0 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
64 
64 
Don't do this unless 
64 
64 
37 
0 
Python Input and Output
If the file might be large, better to read in chunks 
reader = open('haiku.txt', 'r') 
data = reader.read(64) 
Don't do this unless the file really 
might be very large (or infinite) 
wwwwhhhhiiiilllleeee data != '': 
pppprrrriiiinnnntttt len(data) 
data = reader.read(64) 
pppprrrriiiinnnntttt len(data) 
reader.close() 
64 
64 
64 64 
37 
0 
Python Input and Output
More common to read one line at a time 
Python Input and Output
More common to read one line at a time 
reader = open('haiku.txt', 'r') 
line = reader.readline() 
total = 0 
count = 0 
wwwwhhhhiiiilllleeee line != '': 
count += 1 
total += len(line) 
line = reader.readline() 
reader.close() 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
More common to read one line at a time 
reader = open('haiku.txt', 'r') 
line = reader.readline() Read a single line 
total = 0 
count = 0 
wwwwhhhhiiiilllleeee line != '': 
count += 1 
total += len(line) 
line = reader.readline() 
reader.close() 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
More common to read one line at a time 
reader = open('haiku.txt', 'r') 
line = reader.readline() 
total = 0 
count = 0 
wwwwhhhhiiiilllleeee line != '': 
count += 1 
total += len(line) 
line = reader.readline() 
reader.close() 
Keep looping until 
no more lines in file 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
More common to read one line at a time 
reader = open('haiku.txt', 'r') 
line = reader.readline() 
total = 0 
count = 0 
wwwwhhhhiiiilllleeee line != '': 
count += 1 
total += len(line) 
line = reader.readline() 
reader.close() 
(Try to) reload 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
More common to read one line at a time 
reader = open('haiku.txt', 'r') 
line = reader.readline() 
total = 0 
count = 0 
wwwwhhhhiiiilllleeee line != '': 
count += 1 
total += len(line) 
line = reader.readline() 
reader.close() 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
19.53333333 
Python Input and Output
Often more convenient to read all lines at once 
Python Input and Output
Often more convenient to read all lines at once 
reader = open('haiku.txt', 'r') 
contents = reader.readlines() 
reader.close() 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn contents: 
count += 1 
total += len(line) 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
Often more convenient to read all lines at once 
reader = open('haiku.txt', 'r') 
contents = reader.readlines() All lines in file 
reader.close() 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn contents: 
count += 1 
total += len(line) 
as list of strings 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
Often more convenient to read all lines at once 
reader = open('haiku.txt', 'r') 
contents = reader.readlines() Loop over lines 
reader.close() 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn contents: 
count += 1 
total += len(line) 
with for 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
Often more convenient to read all lines at once 
reader = open('haiku.txt', 'r') 
contents = reader.readlines() 
reader.close() 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn contents: 
count += 1 
total += len(line) 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
19.53333333 
Python Input and Output
"Read lines as list" + "loop over list" is common idiom 
Python Input and Output
"Read lines as list" + "loop over list" is common idiom 
So Python provides "loop over lines in file" 
Python Input and Output
"Read lines as list" + "loop over list" is common idiom 
So Python provides "loop over lines in file" 
reader = open('haiku.txt', 'r') 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn reader: 
count += 1 
total += len(line) 
reader.close() 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
"Read lines as list" + "loop over list" is common idiom 
So Python provides "loop over lines in file" 
reader = open('haiku.txt', 'r') 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn reader: 
count += 1 
total += len(line) 
Assign lines of text in file 
to loop variable one by one 
reader.close() 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
Python Input and Output
"Read lines as list" + "loop over list" is common idiom 
So Python provides "loop over lines in file" 
reader = open('haiku.txt', 'r') 
total = 0 
count = 0 
ffffoooorrrr line iiiinnnn reader: 
count += 1 
total += len(line) 
reader.close() 
pppprrrriiiinnnntttt 'average', float(total) / float(count) 
19.53333333 
Python Input and Output
Python Input and Output
Put data in a file using write or writelines 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
Same function 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
File to write to 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
File to write to 
Created if it doesn't exist 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
For writing instead 
of reading 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
Write a single string 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
Write each string 
in a list 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
elementsHeNeArKr 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elements') 
writer.writelines(['He', 'Ne', 'Ar', 'Kr']) 
writer.close() 
elementsHeNeArKr 
Python only writes what you tell it to 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elementsn') 
writer.writelines(['Hen', 'Nen', 'Arn', 'Krn']) 
writer.close() 
Have to provide end-of-line characters yourself 
Python Input and Output
Put data in a file using write or writelines 
writer = open('temp.txt', 'w') 
writer.write('elementsn') 
writer.writelines(['Hen', 'Nen', 'Arn', 'Krn']) 
writer.close() 
elements 
He 
Ne 
Ar 
Kr 
Python Input and Output
Often simpler to use print >> 
Python Input and Output
Often simpler to use print >> 
writer = open('temp.txt', 'w') 
pppprrrriiiinnnntttt >> writer, 'elements' 
ffffoooorrrr gas iiiinnnn ['He', 'Ne', 'Ar', 'Kr']: 
pppprrrriiiinnnntttt >> writer, gas 
writer.close() 
Python Input and Output
Often simpler to use print >> 
writer = open('temp.txt', 'w') 
pppprrrriiiinnnntttt >> writer, 'elements' 
ffffoooorrrr gas iiiinnnn ['He', 'Ne', 'Ar', 'Kr']: 
pppprrrriiiinnnntttt >> writer, gas 
writer.close() 
Specify open file after >> 
Python Input and Output
Often simpler to use print >> 
writer = open('temp.txt', 'w') 
pppprrrriiiinnnntttt >> writer, 'elements' 
ffffoooorrrr gas iiiinnnn ['He', 'Ne', 'Ar', 'Kr']: 
pppprrrriiiinnnntttt >> writer, gas 
writer.close() 
print automatically adds the newline 
Python Input and Output
Copy a file 
Python Input and Output
Copy a file 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
writer = open('temp.txt', 'w') 
write.write(data) 
writer.close() 
Python Input and Output
Copy a file 
reader = open('haiku.txt', 'r') 
data = reader.read() Read all 
reader.close() 
writer = open('temp.txt', 'w') 
write.write(data) 
writer.close() 
Python Input and Output
Copy a file 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
writer = open('temp.txt', 'w') 
write.write(data) 
writer.close() 
Write all 
Python Input and Output
Copy a file 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
writer = open('temp.txt', 'w') 
write.write(data) 
writer.close() 
Probably won't work with a terabyte... 
Python Input and Output
Copy a file 
reader = open('haiku.txt', 'r') 
data = reader.read() 
reader.close() 
writer = open('temp.txt', 'w') 
write.write(data) 
writer.close() 
Probably won't work with a terabyte... 
…but we probably don't care 
Python Input and Output
Copy a file (version 2) 
Python Input and Output
Copy a file (version 2) 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
writer.write(line) 
reader.close() 
writer.close() 
Python Input and Output
Copy a file (version 2) 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
writer.write(line) 
reader.close() 
writer.close() 
Assumes the file is text 
Python Input and Output
Copy a file (version 2) 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
writer.write(line) 
reader.close() 
writer.close() 
Assumes the file is text 
Or at least that the end-of-line character appears 
frequently 
Python Input and Output
This version doesn't make an exact copy 
Python Input and Output
This version doesn't make an exact copy 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
print >> writer, line 
reader.close() 
writer.close() 
Python Input and Output
This version doesn't make an exact copy 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
print >> writer, line 
reader.close() 
writer.close() 
Python keeps the newline when reading 
Python Input and Output
This version doesn't make an exact copy 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
print >> writer, line 
reader.close() 
writer.close() 
Python keeps the newline when reading 
print automatically adds a newline 
Python Input and Output
This version doesn't make an exact copy 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
ffffoooorrrr line iiiinnnn reader: 
print >> writer, line 
reader.close() 
writer.close() 
Python keeps the newline when reading 
print automatically adds a newline 
Result is double-spaced output 
Python Input and Output
Copy a file (version 3) 
Python Input and Output
Copy a file (version 3) 
BLOCKSIZE = 1024 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
data = reader.read(BLOCKSIZE) 
wwwwhhhhiiiilllleeee len(data) > 0: 
writer.write(data) 
data = reader.read(BLOCKSIZE) 
reader.close() 
writer.close() 
Python Input and Output
Copy a file (version 3) 
BLOCKSIZE = 1024 
reader = open('haiku.txt', 'r') 
writer = open('temp.txt', 'w') 
data = reader.read(BLOCKSIZE) 
wwwwhhhhiiiilllleeee len(data) > 0: 
writer.write(data) 
data = reader.read(BLOCKSIZE) 
reader.close() 
writer.close() 
(Needlessly?) harder to understand 
Python Input and Output
created by 
Greg Wilson 
October 2010 
Copyright © Software Carpentry 2010 
This work is licensed under the Creative Commons Attribution License 
See http://software-carpentry.org/license.html for more information.

More Related Content

What's hot

Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In PythonAmit Upadhyay
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPriyaSoundararajan1
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++Neeru Mittal
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming Kamal Acharya
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programmingManoj Tyagi
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaEdureka!
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 

What's hot (20)

Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Python functions
Python functionsPython functions
Python functions
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.ppt
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programming
 
Php functions
Php functionsPhp functions
Php functions
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Functions in python
Functions in python Functions in python
Functions in python
 
Javascript
JavascriptJavascript
Javascript
 
Python basics
Python basicsPython basics
Python basics
 
Report on c
Report on cReport on c
Report on c
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Python : Operators
Python : OperatorsPython : Operators
Python : Operators
 
Dictionary
DictionaryDictionary
Dictionary
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 

Viewers also liked

python Function
python Function python Function
python Function Ronak Rathi
 
Python - Dicionários
Python - DicionáriosPython - Dicionários
Python - DicionáriosMarcos Castro
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
Python datatype
Python datatypePython datatype
Python datatype건희 김
 
4. python functions
4. python   functions4. python   functions
4. python functionsin4400
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentationMartin McBride
 

Viewers also liked (13)

Day2
Day2Day2
Day2
 
Functions
FunctionsFunctions
Functions
 
python Function
python Function python Function
python Function
 
Python - Dicionários
Python - DicionáriosPython - Dicionários
Python - Dicionários
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Python - Set
Python - SetPython - Set
Python - Set
 
Python datatype
Python datatypePython datatype
Python datatype
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 

Similar to Input and Output

File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptRaja Ram Dutta
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxssuserd0df33
 
Python interview questions
Python interview questionsPython interview questions
Python interview questionsPragati Singh
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/OMarc Gouw
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for BioinformaticsJosé Héctor Gálvez
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptRedenOriola
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxAshwini Raut
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekingeProf. Wim Van Criekinge
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdfRashmiAngane1
 

Similar to Input and Output (20)

Libraries
LibrariesLibraries
Libraries
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
005. FILE HANDLING.pdf
005. FILE HANDLING.pdf005. FILE HANDLING.pdf
005. FILE HANDLING.pdf
 
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
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
Python interview questions
Python interview questionsPython interview questions
Python interview questions
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
 
Python-files
Python-filesPython-files
Python-files
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
 

More from Marieswaran Ramasamy (8)

Handouts lecture slides_lecture6_5
Handouts lecture slides_lecture6_5Handouts lecture slides_lecture6_5
Handouts lecture slides_lecture6_5
 
Slicing
SlicingSlicing
Slicing
 
Tuples
TuplesTuples
Tuples
 
Alias
AliasAlias
Alias
 
Strings
StringsStrings
Strings
 
Lists
ListsLists
Lists
 
Basics
BasicsBasics
Basics
 
Control Flow
Control FlowControl Flow
Control Flow
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Input and Output

  • 1. Python Input and Output Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information.
  • 2. Been using print to see what programs are doing Python Input and Output
  • 3. Been using print to see what programs are doing How to save data to files? Python Input and Output
  • 4. Been using print to see what programs are doing How to save data to files? And read ddaattaa ffrroomm tthheemm?? Python Input and Output
  • 5. Been using print to see what programs are doing How to save data to files? And read ddaattaa ffrroomm tthheemm?? Python's solution looks very much like C's Python Input and Output
  • 6. Been using print to see what programs are doing How to save data to files? And read ddaattaa ffrroomm tthheemm?? Python's solution looks very much like C's – A file is a sequence of bytes Python Input and Output
  • 7. Been using print to see what programs are doing How to save data to files? And read ddaattaa ffrroomm tthheemm?? Python's solution looks very much like C's – A file is a sequence of bytes – But it's often more useful to treat it as a sequence of lines Python Input and Output
  • 8. Sample data file Three things are certain: Death, taxes, and lost data. Guess wwhhiicchh hhaass ooccccuurrrreedd.. Errors have occurred. We won't tell you where or why. Lazy programmers. With searching comes loss and the presence of absence: "My Thesis" not found. A crash reduces your expensive computer to a simple stone. Python Input and Output
  • 9. How many characters in a file? Python Input and Output
  • 10. How many characters in a file? bytes Python Input and Output
  • 11. How many characters in a file? bytes Assume 1-to-1 for now Python Input and Output
  • 12. How many characters in a file? bytes Assume 1-to-1 for now RReevviissiitt llaatteerr Python Input and Output
  • 13. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Python Input and Output
  • 14. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Create a file object Python Input and Output
  • 15. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) File to connect to Python Input and Output
  • 16. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) To read Python Input and Output
  • 17. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Now holds file object Python Input and Output
  • 18. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Read entire content of file into a string Python Input and Output
  • 19. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Now has a copy of all the bytes that were in the file Python Input and Output
  • 20. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Disconnect from the file Python Input and Output
  • 21. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Disconnect from the file Not strictly necessary in small programs, but good practice Python Input and Output
  • 22. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Report how many characters were read Python Input and Output
  • 23. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) Report how many characters were read bytes Python Input and Output
  • 24. How many characters in a file? reader = open('haiku.txt', 'r') data = reader.read() reader.close() print len(data) 293 Python Input and Output
  • 25. If the file might be large, better to read in chunks Python Input and Output
  • 26. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() Python Input and Output
  • 27. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) Read (at wwwwhhhhiiiilllleeee data != '': most) 64 bytes pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() Python Input and Output
  • 28. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) Read (at wwwwhhhhiiiilllleeee data != '': most) 64 bytes pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() Or the empty string if there is no more data Python Input and Output
  • 29. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() Keep looping as long as the last read returned some data Python Input and Output
  • 30. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() Do something with the data Python Input and Output
  • 31. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() (Try to) reload Python Input and Output
  • 32. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() Should be 0 (or the loop would still be running) Python Input and Output
  • 33. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() 64 64 64 64 37 0 Python Input and Output
  • 34. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() 64 64 Don't do this unless 64 64 37 0 Python Input and Output
  • 35. If the file might be large, better to read in chunks reader = open('haiku.txt', 'r') data = reader.read(64) Don't do this unless the file really might be very large (or infinite) wwwwhhhhiiiilllleeee data != '': pppprrrriiiinnnntttt len(data) data = reader.read(64) pppprrrriiiinnnntttt len(data) reader.close() 64 64 64 64 37 0 Python Input and Output
  • 36. More common to read one line at a time Python Input and Output
  • 37. More common to read one line at a time reader = open('haiku.txt', 'r') line = reader.readline() total = 0 count = 0 wwwwhhhhiiiilllleeee line != '': count += 1 total += len(line) line = reader.readline() reader.close() pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 38. More common to read one line at a time reader = open('haiku.txt', 'r') line = reader.readline() Read a single line total = 0 count = 0 wwwwhhhhiiiilllleeee line != '': count += 1 total += len(line) line = reader.readline() reader.close() pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 39. More common to read one line at a time reader = open('haiku.txt', 'r') line = reader.readline() total = 0 count = 0 wwwwhhhhiiiilllleeee line != '': count += 1 total += len(line) line = reader.readline() reader.close() Keep looping until no more lines in file pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 40. More common to read one line at a time reader = open('haiku.txt', 'r') line = reader.readline() total = 0 count = 0 wwwwhhhhiiiilllleeee line != '': count += 1 total += len(line) line = reader.readline() reader.close() (Try to) reload pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 41. More common to read one line at a time reader = open('haiku.txt', 'r') line = reader.readline() total = 0 count = 0 wwwwhhhhiiiilllleeee line != '': count += 1 total += len(line) line = reader.readline() reader.close() pppprrrriiiinnnntttt 'average', float(total) / float(count) 19.53333333 Python Input and Output
  • 42. Often more convenient to read all lines at once Python Input and Output
  • 43. Often more convenient to read all lines at once reader = open('haiku.txt', 'r') contents = reader.readlines() reader.close() total = 0 count = 0 ffffoooorrrr line iiiinnnn contents: count += 1 total += len(line) pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 44. Often more convenient to read all lines at once reader = open('haiku.txt', 'r') contents = reader.readlines() All lines in file reader.close() total = 0 count = 0 ffffoooorrrr line iiiinnnn contents: count += 1 total += len(line) as list of strings pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 45. Often more convenient to read all lines at once reader = open('haiku.txt', 'r') contents = reader.readlines() Loop over lines reader.close() total = 0 count = 0 ffffoooorrrr line iiiinnnn contents: count += 1 total += len(line) with for pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 46. Often more convenient to read all lines at once reader = open('haiku.txt', 'r') contents = reader.readlines() reader.close() total = 0 count = 0 ffffoooorrrr line iiiinnnn contents: count += 1 total += len(line) pppprrrriiiinnnntttt 'average', float(total) / float(count) 19.53333333 Python Input and Output
  • 47. "Read lines as list" + "loop over list" is common idiom Python Input and Output
  • 48. "Read lines as list" + "loop over list" is common idiom So Python provides "loop over lines in file" Python Input and Output
  • 49. "Read lines as list" + "loop over list" is common idiom So Python provides "loop over lines in file" reader = open('haiku.txt', 'r') total = 0 count = 0 ffffoooorrrr line iiiinnnn reader: count += 1 total += len(line) reader.close() pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 50. "Read lines as list" + "loop over list" is common idiom So Python provides "loop over lines in file" reader = open('haiku.txt', 'r') total = 0 count = 0 ffffoooorrrr line iiiinnnn reader: count += 1 total += len(line) Assign lines of text in file to loop variable one by one reader.close() pppprrrriiiinnnntttt 'average', float(total) / float(count) Python Input and Output
  • 51. "Read lines as list" + "loop over list" is common idiom So Python provides "loop over lines in file" reader = open('haiku.txt', 'r') total = 0 count = 0 ffffoooorrrr line iiiinnnn reader: count += 1 total += len(line) reader.close() pppprrrriiiinnnntttt 'average', float(total) / float(count) 19.53333333 Python Input and Output
  • 53. Put data in a file using write or writelines Python Input and Output
  • 54. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() Python Input and Output
  • 55. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() Same function Python Input and Output
  • 56. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() File to write to Python Input and Output
  • 57. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() File to write to Created if it doesn't exist Python Input and Output
  • 58. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() For writing instead of reading Python Input and Output
  • 59. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() Write a single string Python Input and Output
  • 60. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() Write each string in a list Python Input and Output
  • 61. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() elementsHeNeArKr Python Input and Output
  • 62. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elements') writer.writelines(['He', 'Ne', 'Ar', 'Kr']) writer.close() elementsHeNeArKr Python only writes what you tell it to Python Input and Output
  • 63. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elementsn') writer.writelines(['Hen', 'Nen', 'Arn', 'Krn']) writer.close() Have to provide end-of-line characters yourself Python Input and Output
  • 64. Put data in a file using write or writelines writer = open('temp.txt', 'w') writer.write('elementsn') writer.writelines(['Hen', 'Nen', 'Arn', 'Krn']) writer.close() elements He Ne Ar Kr Python Input and Output
  • 65. Often simpler to use print >> Python Input and Output
  • 66. Often simpler to use print >> writer = open('temp.txt', 'w') pppprrrriiiinnnntttt >> writer, 'elements' ffffoooorrrr gas iiiinnnn ['He', 'Ne', 'Ar', 'Kr']: pppprrrriiiinnnntttt >> writer, gas writer.close() Python Input and Output
  • 67. Often simpler to use print >> writer = open('temp.txt', 'w') pppprrrriiiinnnntttt >> writer, 'elements' ffffoooorrrr gas iiiinnnn ['He', 'Ne', 'Ar', 'Kr']: pppprrrriiiinnnntttt >> writer, gas writer.close() Specify open file after >> Python Input and Output
  • 68. Often simpler to use print >> writer = open('temp.txt', 'w') pppprrrriiiinnnntttt >> writer, 'elements' ffffoooorrrr gas iiiinnnn ['He', 'Ne', 'Ar', 'Kr']: pppprrrriiiinnnntttt >> writer, gas writer.close() print automatically adds the newline Python Input and Output
  • 69. Copy a file Python Input and Output
  • 70. Copy a file reader = open('haiku.txt', 'r') data = reader.read() reader.close() writer = open('temp.txt', 'w') write.write(data) writer.close() Python Input and Output
  • 71. Copy a file reader = open('haiku.txt', 'r') data = reader.read() Read all reader.close() writer = open('temp.txt', 'w') write.write(data) writer.close() Python Input and Output
  • 72. Copy a file reader = open('haiku.txt', 'r') data = reader.read() reader.close() writer = open('temp.txt', 'w') write.write(data) writer.close() Write all Python Input and Output
  • 73. Copy a file reader = open('haiku.txt', 'r') data = reader.read() reader.close() writer = open('temp.txt', 'w') write.write(data) writer.close() Probably won't work with a terabyte... Python Input and Output
  • 74. Copy a file reader = open('haiku.txt', 'r') data = reader.read() reader.close() writer = open('temp.txt', 'w') write.write(data) writer.close() Probably won't work with a terabyte... …but we probably don't care Python Input and Output
  • 75. Copy a file (version 2) Python Input and Output
  • 76. Copy a file (version 2) reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: writer.write(line) reader.close() writer.close() Python Input and Output
  • 77. Copy a file (version 2) reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: writer.write(line) reader.close() writer.close() Assumes the file is text Python Input and Output
  • 78. Copy a file (version 2) reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: writer.write(line) reader.close() writer.close() Assumes the file is text Or at least that the end-of-line character appears frequently Python Input and Output
  • 79. This version doesn't make an exact copy Python Input and Output
  • 80. This version doesn't make an exact copy reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: print >> writer, line reader.close() writer.close() Python Input and Output
  • 81. This version doesn't make an exact copy reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: print >> writer, line reader.close() writer.close() Python keeps the newline when reading Python Input and Output
  • 82. This version doesn't make an exact copy reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: print >> writer, line reader.close() writer.close() Python keeps the newline when reading print automatically adds a newline Python Input and Output
  • 83. This version doesn't make an exact copy reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') ffffoooorrrr line iiiinnnn reader: print >> writer, line reader.close() writer.close() Python keeps the newline when reading print automatically adds a newline Result is double-spaced output Python Input and Output
  • 84. Copy a file (version 3) Python Input and Output
  • 85. Copy a file (version 3) BLOCKSIZE = 1024 reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') data = reader.read(BLOCKSIZE) wwwwhhhhiiiilllleeee len(data) > 0: writer.write(data) data = reader.read(BLOCKSIZE) reader.close() writer.close() Python Input and Output
  • 86. Copy a file (version 3) BLOCKSIZE = 1024 reader = open('haiku.txt', 'r') writer = open('temp.txt', 'w') data = reader.read(BLOCKSIZE) wwwwhhhhiiiilllleeee len(data) > 0: writer.write(data) data = reader.read(BLOCKSIZE) reader.close() writer.close() (Needlessly?) harder to understand Python Input and Output
  • 87. created by Greg Wilson October 2010 Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information.