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

PPTX
File handling in Python
PPT
Unit5 C
PPT
File handling(some slides only)
PDF
Python - Lecture 8
PDF
PDF
File and directories in python
PDF
Python file handling
PDF
Python programming : Files
File handling in Python
Unit5 C
File handling(some slides only)
Python - Lecture 8
File and directories in python
Python file handling
Python programming : Files

What's hot (20)

PDF
File handling and Dictionaries in python
PPTX
File Handling Python
PPTX
Data file handling in python reading & writing methods
PDF
Python - File operations & Data parsing
PPTX
Data file handling in python introduction,opening & closing files
DOCX
python file handling
PDF
Python File Handling | File Operations in Python | Learn python programming |...
PPT
Filehandlinging cp2
PPT
File Handling In C++(OOPs))
PPTX
Data file handling in c++
PPTX
basics of file handling
PDF
File handling
PPT
File handling in_c
PPSX
Files in c++
PPTX
Chapter 08 data file handling
PPT
File handling
PDF
Python-files
PPT
File handling in C++
File handling and Dictionaries in python
File Handling Python
Data file handling in python reading & writing methods
Python - File operations & Data parsing
Data file handling in python introduction,opening & closing files
python file handling
Python File Handling | File Operations in Python | Learn python programming |...
Filehandlinging cp2
File Handling In C++(OOPs))
Data file handling in c++
basics of file handling
File handling
File handling in_c
Files in c++
Chapter 08 data file handling
File handling
Python-files
File handling in C++
Ad

Viewers also liked (7)

PPTX
Symmetric multiprocessing (smp)
PPTX
Filehandling
PPT
Real time operating system
PPTX
Operating system introducton and tyes
PPTX
Operating System - Types Of Operating System Unit-1
PPTX
Operating Systems
PPT
Fundamental File Processing Operations
Symmetric multiprocessing (smp)
Filehandling
Real time operating system
Operating system introducton and tyes
Operating System - Types Of Operating System Unit-1
Operating Systems
Fundamental File Processing Operations
Ad

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

PPTX
UNIT III PYTHON.pptx python basic ppt ppt
PDF
GE3151_PSPP_UNIT_5_Notes
PPTX
Unit V.pptx
PDF
Python Interview Questions And Answers
PPTX
Python programming
PPTX
Introduction To Programming with Python-5
PPTX
Python files creation read,write Unit 5.pptx
PDF
File handling with python class 12th .pdf
PPT
Python File functions
PPTX
UNIT –5.pptxpython for engineering students
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
01 file handling for class use class pptx
PPTX
File Handling in Python -binary files.pptx
PPTX
file handling in python using exception statement
PPTX
Python Workshop
PPTX
Python UNIT-III-part-1.pptx File Handling
PDF
Module2-Files.pdf
PPTX
Chapter - 5.pptx
PPTX
Python_Unit_III.pptx
PPTX
FILE HANDLING.pptx
UNIT III PYTHON.pptx python basic ppt ppt
GE3151_PSPP_UNIT_5_Notes
Unit V.pptx
Python Interview Questions And Answers
Python programming
Introduction To Programming with Python-5
Python files creation read,write Unit 5.pptx
File handling with python class 12th .pdf
Python File functions
UNIT –5.pptxpython for engineering students
Python Workshop - Learn Python the Hard Way
01 file handling for class use class pptx
File Handling in Python -binary files.pptx
file handling in python using exception statement
Python Workshop
Python UNIT-III-part-1.pptx File Handling
Module2-Files.pdf
Chapter - 5.pptx
Python_Unit_III.pptx
FILE HANDLING.pptx

More from PranavSB (6)

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

Recently uploaded (20)

PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
PPTX
Save Business Costs with CRM Software for Insurance Agents
PDF
Build Multi-agent using Agent Development Kit
PDF
Comprehensive Salesforce Implementation Services.pdf
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
Why Should Businesses Extract Cuisine Types Data from Multiple U.S. Food Apps...
PPTX
Benefits of DCCM for Genesys Contact Center
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Best Mobile App Development Company in Lucknow - Code Crafter Web Solutions
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
PDF
Exploring AI Agents in Process Industries
PDF
Convert Thunderbird to Outlook into bulk
PPTX
Using Bootstrap to Make Accessible Front-Ends(2).pptx
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
DOCX
The Five Best AI Cover Tools in 2025.docx
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Community & News Update Q2 Meet Up 2025
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Micromaid: A simple Mermaid-like chart generator for Pharo
Save Business Costs with CRM Software for Insurance Agents
Build Multi-agent using Agent Development Kit
Comprehensive Salesforce Implementation Services.pdf
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
Why Should Businesses Extract Cuisine Types Data from Multiple U.S. Food Apps...
Benefits of DCCM for Genesys Contact Center
How Creative Agencies Leverage Project Management Software.pdf
Best Mobile App Development Company in Lucknow - Code Crafter Web Solutions
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Exploring AI Agents in Process Industries
Convert Thunderbird to Outlook into bulk
Using Bootstrap to Make Accessible Front-Ends(2).pptx
Materi_Pemrograman_Komputer-Looping.pptx
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
The Five Best AI Cover Tools in 2025.docx
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
PTS Company Brochure 2025 (1).pdf.......
Community & News Update Q2 Meet Up 2025
The Future of Smart Factories Why Embedded Analytics Leads the Way

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