0% found this document useful (0 votes)
11 views

Unit III

Files:
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit III

Files:
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Unit III

Files
Files
• In everyday life, the term “file” is something of a catchall. It is used for
things that are not only written, but also used to describe things that
don’t have any words in them at all, like pictures.
• A file is the common storage unit in a computer, and all programs and
data are “written” into a file and “read” from a file.
• A file extension, sometimes called a file suffix or a filename extension,
is the character or group of characters after the period that makes up
an entire file name.
Types of Files
• Python supports two types of files – text files and binary files. These
two file types may look the same on the surface but they encode data
differently.
• While both binary and text files contain data stored as a series of bits
(binary values of 1s and 0s), the bits in text files represent characters,
while the bits in binary files represent custom data.
Extensions
• Common extensions for binary file formats:
• Images: jpg, png, gif, bmp, tiff, psd,...
• Videos: mp4, mkv, avi, mov, mpg, vob,...
• Audio: mp3, aac, wav, flac, ogg, mka, wma,...
• Documents: pdf, doc, xls, ppt, docx, odt,...
• Archive: zip, rar, 7z, tar, iso,...
• Database: mdb, accde, frm, sqlite,...
• Executable: exe, dll, so, class,...
• Common extensions for text file formats:
• Web standards: html, xml, css, svg, json,...
• Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh,...
• Documents: txt, tex, markdown, asciidoc, rtf, ps,...
• Configuration: ini, cfg, rc, reg,...
• Tabular data: csv, tsv,...
File Paths
Creating and Opening Text Files
Access Modes of the Files
Example
close() Method
Example
Use of with Statements to Open and Close
Files
• Instead of using try-except-finally blocks to handle file opening and
closing operations, a much cleaner way of doing this in Python is
using the with statement.
File Object Attributes
File Methods to Read and Write Data
• When you use the open() function a file object is created.
Cont.,
Cont.,
Reading and Writing Binary Files
How do bytes work?
CSV Files
• CSV files have .csv extensions. Because a CSV is essentially a text file,
it is easy to write data to one with Python.
• Some advantages of CSV files are:
• It is in a human-readable format and is easier to edit manually.
• It is simple to generate, parse and handle.
• It is having a small footprint and is compact.
• It is a standard format and is supported by many applications.
Characteristics of the CSV format
• Each record (also called as row) is located on a separate line, delimited by a
line break (CRLF).
• A line break may or may not be present at the end of the last record in a
file.
• An optional header line may appear as the first line of the file with the
same format as normal record lines.
• Commas are used to separate the fields in each record. Each line should
contain the same number of fields throughout the file.
• Double quotes may or may not be used to enclose each field; however,
some programs, such as Microsoft Excel, do not use double quotes at all. If
fields are not enclosed with double quotes, then the double quotes may
not appear inside the fields.
Reading and Writing CSV Files
CSV Example
The Pickle Module
• Strings can easily be written to and read from a file. Numbers take a bit
more effort since the read() method only returns strings that will have to
be passed to a function like int(), which takes a string like '123' and returns
its numeric value 123.
• However, when you want to save more complex data types like lists,
dictionaries, or class instances, things get a lot more complicated.
• Rather than having the users to constantly write and debug the code to
save complicated data types, Python provides a standard module called
pickle.
• This is an amazing module that can take almost any Python object and
convert it to a string representation; this process is called pickling.
• Reconstructing the object from the string representation is called
unpickling.
The Pickle Module
• The dump() method writes a pickled representation of object x to the
open file object f.
• pickle.dump(x, f)

• If f is a file object, which has been opened for reading, then the
simplest way to unpickle the object is,
• x = pickle.load(f)
• The load() method reads a pickled object representation from the
open file object f and return the reconstituted object hierarchy
specified therein.
Example
Object Oriented Programming
Classes and Objects
Creating Classes in Python
Example
self parameter
• The first parameter in each of these methods is the word self.
• When self is used, it is just a variable name to which the object that
was created based on a class is assigned.
Creating Objects in Python
• Object refers to a particular instance of a class where the object
contains variables and methods defined in the class.
The Constructor Method
• Python uses a special method called a constructor method. Python
allows you to define only one constructor per class.
• Also known as the __init__() method
• The __init__() method defines and initializes the instance variables.
• It is invoked as soon as an object of a class is instantiated
The Constructor Method
Classes with Multiple Objects
• Multiple objects for a class can be created while attaching a unique
copy of data attributes and methods of the class to each of these
objects.
Default Parameters
Class Attributes versus Data Attributes
• Data attributes are instance variables that are unique to each object
of a class,
• Class attributes are class variables that is shared by all objects of a
class.
Example
Encapsulation
• Encapsulation is the process of combining variables that store data
and methods that work on those variables into a single unit called
class.
• In Encapsulation, the variables are not accessed directly; it is accessed
through the methods present in the class.
• Encapsulation ensures that the object’s internal representation (its
state and behavior) are hidden from the rest of the application.
• Thus, encapsulation makes the concept of data hiding possible.
Abstraction
• An application using a class does not need to know its internal
workings or how it is implemented.
• The program simply creates an object and uses it to invoke the
methods of that class.
• Abstraction is a process where you show only “relevant” variables
that are used to access data and “hide” implementation details of an
object from the user.
Abstraction Vs Encapsulation
• Abstraction is a design level process and it is used to reduce the
complexity at the designing stage of a project.
• Encapsulation is an implementation level process, and it is used to
provide privacy and maintain control over the transparency of data at
the implementation stage of a project.
Example
Using Private Instance Variables and Methods
• Instance variables or methods, which can be accessed within the
same class and can’t be seen outside, are called private instance
variables or private methods.
Destructors in Python
• Destructors are called when an object gets destroyed. In Python,
destructors are not needed as much as in C++ because Python has a
garbage collector that handles memory management automatically.
• The __del__() method is a known as a destructor method in Python.
Access Modifiers in Python
• Python access modifiers are used to modify the default scope of a
variable. There are three types of access modifiers in Python and they
are – Public, Private, and Protected. In Python, we
use underscores “_” symbol to specify the access modifier for specific
data members and member functions in the class.
• Public
• Private
• Protected
Public access modifier in Python
• All the members in the Python class are public by default. Any
member declared as public can be accessed from outside the class
through an object.
Private access modifier in Python
• A double underscore “__” makes the variable private as well as secure
and the members of the class which is declared private are accessible
within the class.
Protected access modifier in Python
• The data member of the class is declared protected by adding a single
underscore “_” and this prevents it from being access. The protected
members of the class can be accessed by other members within the
class also it can be accessible to the class derived from it.
Inheritance
• Inheritance enables new classes to receive or inherit variables and
methods of existing classes.
• A class that is used as the basis for inheritance is called a superclass or base
class.
• A class that inherits from a base class is called a subclass or derived class.
• The terms parent class and child class are also acceptable terms to use
respectively.
• A derived class inherits variables and methods from its base class while
adding additional variables and methods of its own.
• Inheritance easily enables reusing of existing code.
Syntax
Syntax
Example
Types of Inheritance in Python
Types of Inheritance in Python
Types of Inheritance

Hybrid Inheritance
Example
Accessing the Inherited Variables and
Methods
Polymorphism
• The word polymorphism means having many forms.
• In programming, polymorphism means the same function name (but
different signatures) being used for different types.
• The key difference is the data types and number of arguments used in
function.
Example of inbuilt polymorphic functions:
# Python program to demonstrate in-built poly- # morphic functions

# len() being used for a string


print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))
Examples of user-defined polymorphic
functions
# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z = 0):


return x + y+z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Polymorphism
with class
methods
Polymorphism
with Inheritance
• Method Overiding

You might also like