SlideShare a Scribd company logo
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

Python pandas tutorial
Python pandas tutorialPython pandas tutorial
Python pandas tutorial
HarikaReddy115
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Yi-Fan Chu
 
USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Python
PythonPython
Python
Aashish Jain
 
Python basics
Python basicsPython basics
Python basics
RANAALIMAJEEDRAJPUT
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
Sabik T S
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
C++
C++C++
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
Elewayte
 
Function in Python
Function in PythonFunction in Python
Function in Python
Yashdev Hada
 
Python : Data Types
Python : Data TypesPython : Data Types
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
Python
PythonPython
Python
SHIVAM VERMA
 

What's hot (20)

Python pandas tutorial
Python pandas tutorialPython pandas tutorial
Python pandas tutorial
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python
PythonPython
Python
 
Python basics
Python basicsPython basics
Python basics
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
C++
C++C++
C++
 
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Python
PythonPython
Python
 

Viewers also liked

Day2
Day2Day2
Functions
FunctionsFunctions
python Function
python Function python Function
python Function
Ronak Rathi
 
Python - Dicionários
Python - DicionáriosPython - Dicionários
Python - Dicionários
Marcos Castro
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Python - Set
Python - SetPython - Set
Python - Set
Marcos Castro
 
Python datatype
Python datatypePython datatype
Python datatype
건희 김
 
4. python functions
4. python   functions4. python   functions
4. python functions
in4400
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
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 Python
Sujith Kumar
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
Martin McBride
 

Viewers also liked (15)

Day2
Day2Day2
Day2
 
Functions in python
Functions in python Functions in python
Functions in python
 
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
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 

Similar to Input and Output

Libraries
LibrariesLibraries
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
005. FILE HANDLING.pdf
005. FILE HANDLING.pdf005. FILE HANDLING.pdf
005. FILE HANDLING.pdf
noormuhammad101340
 
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
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
Python interview questions
Python interview questionsPython interview questions
Python interview questions
Pragati Singh
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
Marc Gouw
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
Maxym Kharchenko
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
José 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;reuge
vsol7206
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
RedenOriola
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
Saket Choudhary
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
Prof. Wim Van Criekinge
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
Mattupallipardhu
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 

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

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

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

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 

Recently uploaded (20)

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 

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.