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

basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 

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 (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 Files and file objects (in Python)

Similar to Files and file objects (in Python) (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

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 

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 b.pranavshankar@gmail.com Telegram - @pranavsb