SlideShare a Scribd company logo
1 of 15
Files
Python SIG – PYA
Class 5 – 7/11/15
(Revision of) Tuples
• Tuples are “immutable lists”
• A tuple is not ‘()’ it is ‘,’
• ‘count’ and ‘index’ methods
• You can slice, and (negative) index tuples, like lists
• You can use ‘in’ to see if a tuple contains a
particular element
• You can convert a list to a tuple and vice versa
with tuple() and list()
(Revision of) Dictionaries
• key – value pairs
• keys have to be immutable
• values don’t
• dict methods – mainly .keys(), .values() and
.items()
• They return a list, list and list of tuples
repectively
(Revision of) Dictionaries
• dict[valid_key] = corresponding_value
• dict[invalid_key] gives a KeyError
• .get(key, default_value) when we don’t want
the program crashing because of KeyErrors
• .keys() won’t return alphabetically sorted list
• Can use sorted() or .sort()
• sorted() preferred (other won’t work in Py3)
(Revision of) try except else finally
try:
#potentially dangerous code
except TypeError, err_info:
print 'type’, err_info
except ImportError, err_info:
print ‘import’, err_info
else:
print ‘no errors’
finally: # cleanup code (like closing a file)
(Revision of) assert
• assert condition, ‘Error info’
• If condition evaluates to False, an
AssertionError occurs
• To make program “fail fast”
• You’ll know where it happened
(Revision of) raise
• raise Exception(“Error!”)
• Again, “fail fast”
• Can replace error description with our own
• A list of exceptions can be found on the online
documentation –
https://docs.python.org/2/library/exceptions.
html
(Revision of) with
• Mainly used for file r/w operations
• Alternative to try except in these cases
• with open(‘filename.txt’) as f1:
f1.close()
FileIO
• File objects are used for rw operations
• f1 = open(‘filename.txt’, ‘r’)
• (no, not that f1)
• ‘r’ is by default
• ‘w’ creates file if it doesn’t exist, erases if it
does
• ‘a’ is used to preserve data
Assignment
• Write a program in the Python interpreter to
print the name and information in help() of all
file methods that do not start with ‘__’ (two
underscores).
• To those who have finished, read them!
Files and File objects
• .read() is useful if the file is small. (basically,
can fit in RAM) It reads the entire file as a
string.
• .readline() reads a single line. (defined by line
endings n r rn depending on OS)
• .readlines() returns a list of all lines
• .seek(0) goes to the beginning of the file
• Think of the file object as a DVD player
Files and File objects
• .write() and .writelines() are used to write to a
file. The first one takes a string argument and
second one a sequence of strings.
• Don’t forget to add newlines.
• Don’t forget to close files.
• Most of these methods have optional size
arguments.
with
• Files can be opened multiple times
• with open(‘filename.txt’) as f1:
# do something
# no need to end with f1.close()
• Always closes the file; no matter what.
Assignment
• Using a single file object, first read a .txt file
and print its contents. Then ask the user
whether to erase the contents or add
something and extend the file.. Write the
data entered by the user to the file if the user
chooses the second option.
Thanks!
Pranav S Bijapur,
ECE, BMSCE, Bangalore
b.pranavshankar@gmail.com
Telegram - @pranavsb

More Related Content

What's hot

File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in pythonnitamhaske
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methodskeeeerty
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsingFelix Z. Hoffmann
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing fileskeeeerty
 
python file handling
python file handlingpython file handling
python file handlingjhona2z
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Edureka!
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))Papu Kumar
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
File handling in C++
File handling in C++File handling in C++
File handling in C++Hitesh Kumar
 

What's hot (20)

File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
python file handling
python file handlingpython file handling
python file handling
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File handling
File handlingFile handling
File handling
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Files in c++
Files in c++Files in c++
Files in c++
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
File handling
File handlingFile handling
File handling
 
Python-files
Python-filesPython-files
Python-files
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 

Viewers also liked

Symmetric multiprocessing (smp)
Symmetric multiprocessing (smp)Symmetric multiprocessing (smp)
Symmetric multiprocessing (smp)rayhan basher
 
Operating system introducton and tyes
Operating system introducton and tyesOperating system introducton and tyes
Operating system introducton and tyesNancy Verma
 
Operating System - Types Of Operating System Unit-1
Operating System - Types Of Operating System Unit-1Operating System - Types Of Operating System Unit-1
Operating System - Types Of Operating System Unit-1abhinav baba
 
Fundamental File Processing Operations
Fundamental File Processing OperationsFundamental File Processing Operations
Fundamental File Processing OperationsRico
 

Viewers also liked (7)

Symmetric multiprocessing (smp)
Symmetric multiprocessing (smp)Symmetric multiprocessing (smp)
Symmetric multiprocessing (smp)
 
Filehandling
FilehandlingFilehandling
Filehandling
 
Real time operating system
Real time operating systemReal time operating system
Real time operating system
 
Operating system introducton and tyes
Operating system introducton and tyesOperating system introducton and tyes
Operating system introducton and tyes
 
Operating System - Types Of Operating System Unit-1
Operating System - Types Of Operating System Unit-1Operating System - Types Of Operating System Unit-1
Operating System - Types Of Operating System Unit-1
 
Operating Systems
Operating SystemsOperating Systems
Operating Systems
 
Fundamental File Processing Operations
Fundamental File Processing OperationsFundamental File Processing Operations
Fundamental File Processing Operations
 

Similar to PYA Python SIG class on tuples, dictionaries, exceptions, files

Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 
Python first day
Python first dayPython first day
Python first dayfarkhand
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptxssuserc755f1
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...gjcross
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxlemonchoos
 
introduction to python
 introduction to python introduction to python
introduction to pythonJincy Nelson
 
CPP18 - String Parsing
CPP18 - String ParsingCPP18 - String Parsing
CPP18 - String ParsingMichael Heron
 
Intro to data science module 1 r
Intro to data science module 1 rIntro to data science module 1 r
Intro to data science module 1 ramuletc
 
Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Ahmed El-Arabawy
 

Similar to PYA Python SIG class on tuples, dictionaries, exceptions, files (20)

Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python first day
Python first dayPython first day
Python first day
 
Python first day
Python first dayPython first day
Python first day
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptx
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
Basics.ppt
Basics.pptBasics.ppt
Basics.ppt
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Basics R.ppt
Basics R.pptBasics R.ppt
Basics R.ppt
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptx
 
introduction to python
 introduction to python introduction to python
introduction to python
 
CPP18 - String Parsing
CPP18 - String ParsingCPP18 - String Parsing
CPP18 - String Parsing
 
Intro to data science module 1 r
Intro to data science module 1 rIntro to data science module 1 r
Intro to data science module 1 r
 
Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions Course 102: Lecture 13: Regular Expressions
Course 102: Lecture 13: Regular Expressions
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Unit v
Unit vUnit v
Unit v
 

Recently uploaded

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

PYA Python SIG class on tuples, dictionaries, exceptions, files

  • 1. Files Python SIG – PYA Class 5 – 7/11/15
  • 2. (Revision of) Tuples • Tuples are “immutable lists” • A tuple is not ‘()’ it is ‘,’ • ‘count’ and ‘index’ methods • You can slice, and (negative) index tuples, like lists • You can use ‘in’ to see if a tuple contains a particular element • You can convert a list to a tuple and vice versa with tuple() and list()
  • 3. (Revision of) Dictionaries • key – value pairs • keys have to be immutable • values don’t • dict methods – mainly .keys(), .values() and .items() • They return a list, list and list of tuples repectively
  • 4. (Revision of) Dictionaries • dict[valid_key] = corresponding_value • dict[invalid_key] gives a KeyError • .get(key, default_value) when we don’t want the program crashing because of KeyErrors • .keys() won’t return alphabetically sorted list • Can use sorted() or .sort() • sorted() preferred (other won’t work in Py3)
  • 5. (Revision of) try except else finally try: #potentially dangerous code except TypeError, err_info: print 'type’, err_info except ImportError, err_info: print ‘import’, err_info else: print ‘no errors’ finally: # cleanup code (like closing a file)
  • 6. (Revision of) assert • assert condition, ‘Error info’ • If condition evaluates to False, an AssertionError occurs • To make program “fail fast” • You’ll know where it happened
  • 7. (Revision of) raise • raise Exception(“Error!”) • Again, “fail fast” • Can replace error description with our own • A list of exceptions can be found on the online documentation – https://docs.python.org/2/library/exceptions. html
  • 8. (Revision of) with • Mainly used for file r/w operations • Alternative to try except in these cases • with open(‘filename.txt’) as f1: f1.close()
  • 9. FileIO • File objects are used for rw operations • f1 = open(‘filename.txt’, ‘r’) • (no, not that f1) • ‘r’ is by default • ‘w’ creates file if it doesn’t exist, erases if it does • ‘a’ is used to preserve data
  • 10. Assignment • Write a program in the Python interpreter to print the name and information in help() of all file methods that do not start with ‘__’ (two underscores). • To those who have finished, read them!
  • 11. Files and File objects • .read() is useful if the file is small. (basically, can fit in RAM) It reads the entire file as a string. • .readline() reads a single line. (defined by line endings n r rn depending on OS) • .readlines() returns a list of all lines • .seek(0) goes to the beginning of the file • Think of the file object as a DVD player
  • 12. Files and File objects • .write() and .writelines() are used to write to a file. The first one takes a string argument and second one a sequence of strings. • Don’t forget to add newlines. • Don’t forget to close files. • Most of these methods have optional size arguments.
  • 13. with • Files can be opened multiple times • with open(‘filename.txt’) as f1: # do something # no need to end with f1.close() • Always closes the file; no matter what.
  • 14. Assignment • Using a single file object, first read a .txt file and print its contents. Then ask the user whether to erase the contents or add something and extend the file.. Write the data entered by the user to the file if the user chooses the second option.
  • 15. Thanks! Pranav S Bijapur, ECE, BMSCE, Bangalore b.pranavshankar@gmail.com Telegram - @pranavsb