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.
Ad

More Related Content

What's hot (20)

88 c-programs
88 c-programs88 c-programs
88 c-programs
Leandro Schenone
 
Python
PythonPython
Python
Chetan Khanzode
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Saravanan T.M
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
rajshreemuthiah
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
eteaching
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
Devashish Kumar
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Edureka!
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
Vijayananda Mohire
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
Viraj Shah
 
Computer Science:Pointers in C
Computer Science:Pointers in CComputer Science:Pointers in C
Computer Science:Pointers in C
St Mary's College,Thrissur,Kerala
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
PART 1 - Python Tutorial | Variables and Data Types in Python
PART 1 - Python Tutorial | Variables and Data Types in PythonPART 1 - Python Tutorial | Variables and Data Types in Python
PART 1 - Python Tutorial | Variables and Data Types in Python
Shivam Mitra
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
R.h. Himel
 
Python-Functions.pptx
Python-Functions.pptxPython-Functions.pptx
Python-Functions.pptx
Karudaiyar Ganapathy
 
String in c programming
String in c programmingString in c programming
String in c programming
Devan Thakur
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Vijayananda Ratnam Ch
 
C string
C stringC string
C string
University of Potsdam
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
rajshreemuthiah
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
eteaching
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
Devashish Kumar
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Edureka!
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
Viraj Shah
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
PART 1 - Python Tutorial | Variables and Data Types in Python
PART 1 - Python Tutorial | Variables and Data Types in PythonPART 1 - Python Tutorial | Variables and Data Types in Python
PART 1 - Python Tutorial | Variables and Data Types in Python
Shivam Mitra
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
R.h. Himel
 
String in c programming
String in c programmingString in c programming
String in c programming
Devan Thakur
 

Viewers also liked (16)

Day2
Day2Day2
Day2
Karin Lagesen
 
Functions in python
Functions in python Functions in python
Functions in python
baabtra.com - No. 1 supplier of quality freshers
 
Functions
FunctionsFunctions
Functions
Marieswaran Ramasamy
 
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
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
Amit Upadhyay
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian 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
 
Ad

Similar to Input and Output (20)

File methods available in Python Programming
File methods available in Python ProgrammingFile methods available in Python Programming
File methods available in Python Programming
fpriscilla
 
Libraries
LibrariesLibraries
Libraries
Marieswaran Ramasamy
 
this is about file concepts in class 12 in python , text file, binary file, c...
this is about file concepts in class 12 in python , text file, binary file, c...this is about file concepts in class 12 in python , text file, binary file, c...
this is about file concepts in class 12 in python , text file, binary file, c...
Primary2Primary2
 
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
 
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
ssuser0b643d
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
file handlling in python 23.12.24 geetha.pptx
file handlling  in python 23.12.24 geetha.pptxfile handlling  in python 23.12.24 geetha.pptx
file handlling in python 23.12.24 geetha.pptx
vlkumashankardeekshi th
 
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
 
Python_Fundamentals_for_Everyone_Usefull
Python_Fundamentals_for_Everyone_UsefullPython_Fundamentals_for_Everyone_Usefull
Python_Fundamentals_for_Everyone_Usefull
rravipssrivastava
 
Chapter1 python introduction syntax general
Chapter1 python introduction syntax generalChapter1 python introduction syntax general
Chapter1 python introduction syntax general
ssuser77162c
 
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
 
Python knowledge ,......................
Python knowledge ,......................Python knowledge ,......................
Python knowledge ,......................
sabith777a
 
File methods available in Python Programming
File methods available in Python ProgrammingFile methods available in Python Programming
File methods available in Python Programming
fpriscilla
 
this is about file concepts in class 12 in python , text file, binary file, c...
this is about file concepts in class 12 in python , text file, binary file, c...this is about file concepts in class 12 in python , text file, binary file, c...
this is about file concepts in class 12 in python , text file, binary file, c...
Primary2Primary2
 
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
 
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
ssuser0b643d
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
file handlling in python 23.12.24 geetha.pptx
file handlling  in python 23.12.24 geetha.pptxfile handlling  in python 23.12.24 geetha.pptx
file handlling in python 23.12.24 geetha.pptx
vlkumashankardeekshi th
 
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
 
Python_Fundamentals_for_Everyone_Usefull
Python_Fundamentals_for_Everyone_UsefullPython_Fundamentals_for_Everyone_Usefull
Python_Fundamentals_for_Everyone_Usefull
rravipssrivastava
 
Chapter1 python introduction syntax general
Chapter1 python introduction syntax generalChapter1 python introduction syntax general
Chapter1 python introduction syntax general
ssuser77162c
 
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
 
Python knowledge ,......................
Python knowledge ,......................Python knowledge ,......................
Python knowledge ,......................
sabith777a
 
Ad

More from Marieswaran Ramasamy (8)

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

Recently uploaded (20)

Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 

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.