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

PDF
File handling and Dictionaries in python
nitamhaske
 
PPTX
File Handling Python
Akhil Kaushik
 
PPTX
Data file handling in python reading & writing methods
keeeerty
 
PDF
Python - File operations & Data parsing
Felix Z. Hoffmann
 
PPTX
Data file handling in python introduction,opening & closing files
keeeerty
 
DOCX
python file handling
jhona2z
 
PDF
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
PPT
Filehandlinging cp2
Tanmay Baranwal
 
PPT
File Handling In C++(OOPs))
Papu Kumar
 
PPTX
Data file handling in c++
Vineeta Garg
 
PPTX
basics of file handling
pinkpreet_kaur
 
PDF
File handling
Swarup Kumar Boro
 
PPT
File handling in_c
sanya6900
 
PPSX
Files in c++
Selvin Josy Bai Somu
 
PPTX
Chapter 08 data file handling
Praveen M Jigajinni
 
PPT
File handling
Nilesh Dalvi
 
PDF
Python-files
Krishna Nanda
 
PPT
File handling in C++
Hitesh Kumar
 
File handling and Dictionaries in python
nitamhaske
 
File Handling Python
Akhil Kaushik
 
Data file handling in python reading & writing methods
keeeerty
 
Python - File operations & Data parsing
Felix Z. Hoffmann
 
Data file handling in python introduction,opening & closing files
keeeerty
 
python file handling
jhona2z
 
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Filehandlinging cp2
Tanmay Baranwal
 
File Handling In C++(OOPs))
Papu Kumar
 
Data file handling in c++
Vineeta Garg
 
basics of file handling
pinkpreet_kaur
 
File handling
Swarup Kumar Boro
 
File handling in_c
sanya6900
 
Files in c++
Selvin Josy Bai Somu
 
Chapter 08 data file handling
Praveen M Jigajinni
 
File handling
Nilesh Dalvi
 
Python-files
Krishna Nanda
 
File handling in C++
Hitesh Kumar
 

Viewers also liked (7)

PPTX
Symmetric multiprocessing (smp)
rayhan basher
 
PPTX
Filehandling
Amandeep Kaur
 
PPT
Real time operating system
Shailendra Nagori
 
PPTX
Operating system introducton and tyes
Nancy Verma
 
PPTX
Operating System - Types Of Operating System Unit-1
abhinav baba
 
PPTX
Operating Systems
Harshith Meela
 
PPT
Fundamental File Processing Operations
Rico
 
Symmetric multiprocessing (smp)
rayhan basher
 
Filehandling
Amandeep Kaur
 
Real time operating system
Shailendra Nagori
 
Operating system introducton and tyes
Nancy Verma
 
Operating System - Types Of Operating System Unit-1
abhinav baba
 
Operating Systems
Harshith Meela
 
Fundamental File Processing Operations
Rico
 
Ad

Similar to Files and file objects (in Python) (20)

PPTX
UNIT III PYTHON.pptx python basic ppt ppt
SuganthiDPSGRKCW
 
PDF
GE3151_PSPP_UNIT_5_Notes
Guru Nanak Technical Institutions
 
PPTX
Unit V.pptx
ShaswatSurya
 
PDF
Python Interview Questions And Answers
H2Kinfosys
 
PPTX
Python programming
saroja20
 
PPTX
Introduction To Programming with Python-5
Syed Farjad Zia Zaidi
 
PPTX
Python files creation read,write Unit 5.pptx
shakthi10
 
PDF
File handling with python class 12th .pdf
lionsconvent1234
 
PPT
Python File functions
keerthanakommera1
 
PPTX
UNIT –5.pptxpython for engineering students
SabarigiriVason
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PPTX
01 file handling for class use class pptx
PreeTVithule1
 
PPTX
File Handling in Python -binary files.pptx
deepa63690
 
PPTX
file handling in python using exception statement
srividhyaarajagopal
 
PPTX
Python Workshop
Assem CHELLI
 
PPTX
Python UNIT-III-part-1.pptx File Handling
SrinuTelugu
 
PDF
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
PPTX
Chapter - 5.pptx
MikialeTesfamariam
 
PPTX
Python_Unit_III.pptx
ssuserc755f1
 
PPTX
FILE HANDLING.pptx
kendriyavidyalayano24
 
UNIT III PYTHON.pptx python basic ppt ppt
SuganthiDPSGRKCW
 
GE3151_PSPP_UNIT_5_Notes
Guru Nanak Technical Institutions
 
Unit V.pptx
ShaswatSurya
 
Python Interview Questions And Answers
H2Kinfosys
 
Python programming
saroja20
 
Introduction To Programming with Python-5
Syed Farjad Zia Zaidi
 
Python files creation read,write Unit 5.pptx
shakthi10
 
File handling with python class 12th .pdf
lionsconvent1234
 
Python File functions
keerthanakommera1
 
UNIT –5.pptxpython for engineering students
SabarigiriVason
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
01 file handling for class use class pptx
PreeTVithule1
 
File Handling in Python -binary files.pptx
deepa63690
 
file handling in python using exception statement
srividhyaarajagopal
 
Python Workshop
Assem CHELLI
 
Python UNIT-III-part-1.pptx File Handling
SrinuTelugu
 
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
Chapter - 5.pptx
MikialeTesfamariam
 
Python_Unit_III.pptx
ssuserc755f1
 
FILE HANDLING.pptx
kendriyavidyalayano24
 
Ad

More from PranavSB (6)

PPTX
Short Tech Quiz
PranavSB
 
PPTX
Short Tech Quiz
PranavSB
 
PPTX
Tuples, Dicts and Exception Handling
PranavSB
 
PPTX
Functions, List and String methods
PranavSB
 
PPTX
if, while and for in Python
PranavSB
 
PPTX
What is Python?
PranavSB
 
Short Tech Quiz
PranavSB
 
Short Tech Quiz
PranavSB
 
Tuples, Dicts and Exception Handling
PranavSB
 
Functions, List and String methods
PranavSB
 
if, while and for in Python
PranavSB
 
What is Python?
PranavSB
 

Recently uploaded (20)

PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Import Data Form Excel to Tally Services
Tally xperts
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 

Files and file objects (in Python)

  • 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 [email protected] Telegram - @pranavsb