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

Mais conteúdo relacionado

Mais procurados (20)

Intro to html
Intro to htmlIntro to html
Intro to html
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Python list
Python listPython list
Python list
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
HTML & CSS
HTML & CSSHTML & CSS
HTML & CSS
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Html Basic Tags
Html Basic TagsHtml Basic Tags
Html Basic Tags
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Html text and formatting
Html text and formattingHtml text and formatting
Html text and formatting
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Html list.
Html list.Html list.
Html list.
 

Destaque (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
 

Semelhante a Input and Output

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

Semelhante a 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
 

Mais de 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
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

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.