The document discusses files in Python. It defines a file as an object that stores data, information, settings or commands used with a computer program. There are two main types of files - text files which store data as strings, and binary files which store data as bytes. The document outlines how to open, read, write, append, close and manipulate files in Python using functions like open(), read(), write(), close() etc. It also discusses pickling and unpickling objects to binary files for serialization. Finally, it covers working with directories and running other programs from Python.
The document discusses file handling in Python. It covers opening and closing files, reading and writing to files, and different file access modes. It describes opening files using the open() function and closing files using the close() method. It explains how to read from files using methods like read(), readline(), and readlines(). It also covers writing to files using write(), writelines(), and seeking to specific positions using seek() and tell(). The document provides examples of reading, writing, and manipulating text files in Python.
Python Modules
Python Package
Python File I/O
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for e.g.: filename.py, is called a module and its module name would be filename.
We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their definitions into different programs.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
This document provides an overview of functions and file handling in Python. It discusses defining user-defined functions with the def keyword, including passing arguments, default arguments, keyword arguments, and variable number of arguments. It also covers recursion, anonymous functions, and attributes of file objects. For file handling, it explains opening, reading, writing, and appending files, as well as the different file modes.
File handling in Python allows programs to work with files stored on disk by performing operations like opening, reading, writing, and modifying files. The open() function is used to open a file and return a file object, which can then be used to read or write to the file. There are different file access modes like 'r' for read-only, 'w' for write-only, and 'a' for append. Common methods for reading files include read() to read characters, readline() to read one line, and readlines() to read all lines into a list. Files can be written to using write() and writelines() methods and deleted using functions in the os, shutil, or pathlib modules.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This document provides information on file handling and dictionaries in Python. It discusses file paths, opening and closing files, reading from and writing to files. It also covers creating, accessing, adding, updating and deleting elements in dictionaries. Finally, it discusses directory methods like getcwd(), chdir(), listdir(), mkdir(), rmdir() and rename() for working with directories in Python.
The document provides information about file pointers in C++. It states that a file pointer indicates the position in a file being accessed by a program. File pointers allow programs to move around within a file to read or write data at different locations. Some key functions that manipulate file pointers are seekg(), tellg(), seekp(), and tellp(). These functions respectively allow seeking to a particular location in a file for reading or writing, and returning the current file position. Precise control over file pointers is important when working with random access file I/O in C++.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
Modules are wrappers around Ruby code that cannot be instantiated. They are used to bundle logically related objects together and provide namespaces to avoid naming conflicts. Modules can also be used as mixins by including them in classes to add additional functionality. The document provides examples of using modules as namespaces and mixins, and discusses how to load, require, and include modules from separate files. It also covers how the Enumerable and Comparable modules can be included to add common iteration and comparison methods to classes.
Here are the answers to the quiz questions:
1. def read_file(file_name):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
return lines
2. def input_list():
n = int(input("Enter number of elements : "))
list1 = []
for i in range(0, n):
ele = float(input())
list1.append(ele)
return list1
def output_list(list1):
for i in list1:
print(i)
3. def display_file(filename):
with open(filename
This document discusses fundamentals of low-level I/O and process creation in Unix systems. It covers:
1) Low-level I/O using system calls for opening, reading, writing and moving within files using file descriptors.
2) Program creation and execution using the exec family of system calls to launch new programs and fork() to create new processes from the parent process.
3) Process termination and waiting for child processes to finish using system calls.
This document discusses fundamentals of low-level I/O and process creation in Unix systems. It covers:
1) Low-level I/O using system calls for opening, reading, writing and moving within files using file descriptors.
2) Program creation and execution using the exec family of system calls to launch new programs and fork() to create new processes from the parent process.
3) Process termination and waiting for child processes to finish using system calls.
This document discusses fundamentals of programming with files in Python. It covers opening and reading files, line by line processing, writing to files, and using the CSV module. Key points include opening a file returns a file handle, the for loop efficiently reads files line by line, writing requires opening in 'w' mode, and the CSV module supports reading and writing comma separated value files.
Python programming computer science and engineeringIRAH34
Python supports object-oriented programming (OOP) through classes and objects. A class defines the attributes and behaviors of an object, while an object is an instance of a class. Inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables classes to define common methods that can behave differently depending on the type of object. Operator overloading allows classes to define how operators like + work on class objects.
This document discusses file input and output (I/O) in C++. It explains that a file contains a collection of related data stored on disk and is accessed using input and output pointers. It describes functions for manipulating these pointers like seekg(), seekp(), tellg(), and tellp(). It also covers reading and writing single characters and blocks of data using functions like put(), get(), write(), and read(). Finally, it discusses using command line arguments to specify file names and handling errors in file I/O.
The document provides information about file handling in Python. It discusses the basic operations on files like opening, reading, writing and closing files. It explains text files and binary files, different file access modes, and methods to read and write data from/to files like readline(), readlines(), read(), write() and writelines(). It also covers random access methods like seek() and tell() as well as pickling and unpickling using the pickle module. Finally, it highlights the differences between text and binary files.
The document discusses data file handling in Python. It covers the basics of opening, reading from, and writing to both text and binary files.
The key points covered include: opening and closing files, different file access modes, reading methods like readline(), readlines(), and read(), writing methods like write() and writelines(), random access methods like seek() and tell(), pickling and unpickling using the pickle module, and the differences between text and binary files.
A short update and next week. I am writing both Session 9 and Orientation S1.
As a Guest Student,
You are now upgraded to Grad Level.
See Uploads for “Student Checkin” & “S8”. Thx.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters. We are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
Session Practice, For Reference:
Before starting a session, Make sure to check your environment. Nothing stressful. Later, You can decorate a space as well.
Check the comfort level, any needed resources (Yoga/Reiki/Spa Props), or Meditation Asst?
Props can be oils, sage, incense, candles, crystals, pillows, blankets, yoga mat, any theme applies.
Select your comfort Pose. This can be standing, sitting, laying down, or a combination.
Monitor your breath. You can add exercises.
Add any mantras or affirmations. This does aid mind and spirit. It helps you to focus.
Also you can set intentions using a candle.
The Yoga-key is balancing mind, body, and spirit.
Finally, The Duration can be long or short.
Its a good session base for any style.
Next Week’s Focus:
A continuation of Intuition Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
For Sponsor,
General updates,
& Donations:
Please visit:
https://ldmchapels.weebly.com
File handling in Python allows programs to work with files stored on disk by performing operations like opening, reading, writing, and modifying files. The open() function is used to open a file and return a file object, which can then be used to read or write to the file. There are different file access modes like 'r' for read-only, 'w' for write-only, and 'a' for append. Common methods for reading files include read() to read characters, readline() to read one line, and readlines() to read all lines into a list. Files can be written to using write() and writelines() methods and deleted using functions in the os, shutil, or pathlib modules.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This document provides information on file handling and dictionaries in Python. It discusses file paths, opening and closing files, reading from and writing to files. It also covers creating, accessing, adding, updating and deleting elements in dictionaries. Finally, it discusses directory methods like getcwd(), chdir(), listdir(), mkdir(), rmdir() and rename() for working with directories in Python.
The document provides information about file pointers in C++. It states that a file pointer indicates the position in a file being accessed by a program. File pointers allow programs to move around within a file to read or write data at different locations. Some key functions that manipulate file pointers are seekg(), tellg(), seekp(), and tellp(). These functions respectively allow seeking to a particular location in a file for reading or writing, and returning the current file position. Precise control over file pointers is important when working with random access file I/O in C++.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
Modules are wrappers around Ruby code that cannot be instantiated. They are used to bundle logically related objects together and provide namespaces to avoid naming conflicts. Modules can also be used as mixins by including them in classes to add additional functionality. The document provides examples of using modules as namespaces and mixins, and discusses how to load, require, and include modules from separate files. It also covers how the Enumerable and Comparable modules can be included to add common iteration and comparison methods to classes.
Here are the answers to the quiz questions:
1. def read_file(file_name):
lines = []
with open(file_name, 'r') as f:
for line in f:
lines.append(line)
return lines
2. def input_list():
n = int(input("Enter number of elements : "))
list1 = []
for i in range(0, n):
ele = float(input())
list1.append(ele)
return list1
def output_list(list1):
for i in list1:
print(i)
3. def display_file(filename):
with open(filename
This document discusses fundamentals of low-level I/O and process creation in Unix systems. It covers:
1) Low-level I/O using system calls for opening, reading, writing and moving within files using file descriptors.
2) Program creation and execution using the exec family of system calls to launch new programs and fork() to create new processes from the parent process.
3) Process termination and waiting for child processes to finish using system calls.
This document discusses fundamentals of low-level I/O and process creation in Unix systems. It covers:
1) Low-level I/O using system calls for opening, reading, writing and moving within files using file descriptors.
2) Program creation and execution using the exec family of system calls to launch new programs and fork() to create new processes from the parent process.
3) Process termination and waiting for child processes to finish using system calls.
This document discusses fundamentals of programming with files in Python. It covers opening and reading files, line by line processing, writing to files, and using the CSV module. Key points include opening a file returns a file handle, the for loop efficiently reads files line by line, writing requires opening in 'w' mode, and the CSV module supports reading and writing comma separated value files.
Python programming computer science and engineeringIRAH34
Python supports object-oriented programming (OOP) through classes and objects. A class defines the attributes and behaviors of an object, while an object is an instance of a class. Inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables classes to define common methods that can behave differently depending on the type of object. Operator overloading allows classes to define how operators like + work on class objects.
This document discusses file input and output (I/O) in C++. It explains that a file contains a collection of related data stored on disk and is accessed using input and output pointers. It describes functions for manipulating these pointers like seekg(), seekp(), tellg(), and tellp(). It also covers reading and writing single characters and blocks of data using functions like put(), get(), write(), and read(). Finally, it discusses using command line arguments to specify file names and handling errors in file I/O.
The document provides information about file handling in Python. It discusses the basic operations on files like opening, reading, writing and closing files. It explains text files and binary files, different file access modes, and methods to read and write data from/to files like readline(), readlines(), read(), write() and writelines(). It also covers random access methods like seek() and tell() as well as pickling and unpickling using the pickle module. Finally, it highlights the differences between text and binary files.
The document discusses data file handling in Python. It covers the basics of opening, reading from, and writing to both text and binary files.
The key points covered include: opening and closing files, different file access modes, reading methods like readline(), readlines(), and read(), writing methods like write() and writelines(), random access methods like seek() and tell(), pickling and unpickling using the pickle module, and the differences between text and binary files.
A short update and next week. I am writing both Session 9 and Orientation S1.
As a Guest Student,
You are now upgraded to Grad Level.
See Uploads for “Student Checkin” & “S8”. Thx.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters. We are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
Session Practice, For Reference:
Before starting a session, Make sure to check your environment. Nothing stressful. Later, You can decorate a space as well.
Check the comfort level, any needed resources (Yoga/Reiki/Spa Props), or Meditation Asst?
Props can be oils, sage, incense, candles, crystals, pillows, blankets, yoga mat, any theme applies.
Select your comfort Pose. This can be standing, sitting, laying down, or a combination.
Monitor your breath. You can add exercises.
Add any mantras or affirmations. This does aid mind and spirit. It helps you to focus.
Also you can set intentions using a candle.
The Yoga-key is balancing mind, body, and spirit.
Finally, The Duration can be long or short.
Its a good session base for any style.
Next Week’s Focus:
A continuation of Intuition Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
For Sponsor,
General updates,
& Donations:
Please visit:
https://ldmchapels.weebly.com
How to Create Time Off Request in Odoo 18 Time OffCeline George
Odoo 18 provides an efficient way to manage employee leave through the Time Off module. Employees can easily submit requests, and managers can approve or reject them based on company policies.
Coleoptera, commonly known as beetles, is the largest order of insects, comprising approximately 400,000 described species. Beetles can be found in almost every habitat on Earth, exhibiting a wide range of morphological, behavioral, and ecological diversity. They have a hardened exoskeleton, with the forewings modified into elytra that protect the hind wings. Beetles play important roles in ecosystems as decomposers, pollinators, and food sources for other animals, while some species are considered pests in agriculture and forestry.
How to Create a Stage or a Pipeline in Odoo 18 CRMCeline George
In Odoo, the CRM (Customer Relationship Management) module’s pipeline is a visual representation of a company's sales process that helps sales teams track and manage their interactions with potential customers.
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...parmarjuli1412
The document provides an overview of therapeutic communication, emphasizing its importance in nursing to address patient needs and establish effective relationships. THERAPEUTIC COMMUNICATION included some topics like introduction of COMMUNICATION, definition, types, process of communication, definition therapeutic communication, goal, techniques of therapeutic communication, non-therapeutic communication, few ways to improved therapeutic communication, characteristics of therapeutic communication, barrier of THERAPEUTIC RELATIONSHIP, introduction of interpersonal relationship, types of IPR, elements/ dynamics of IPR, introduction of therapeutic nurse patient relationship, definition, purpose, elements/characteristics , and phases of therapeutic communication, definition of Johari window, uses, what actually model represent and its areas, THERAPEUTIC IMPASSES and its management in 5th semester Bsc. nursing and 2nd GNM students
Rose Cultivation Practices by Kushal Lamichhane.pdfkushallamichhame
This includes the overall cultivation practices of Rose prepared by:
Kushal Lamichhane (AKL)
Instructor
Shree Gandhi Adarsha Secondary School
Kageshowri Manohara-09, Kathmandu, Nepal
Completed Sunday 6/8. For Weekend 6/14 & 15th. (Fathers Day Weekend US.) These workshops are also timeless for future students TY. No admissions needed.
A 9th FREE WORKSHOP
Reiki - Yoga
“Intuition-II, The Chakras”
Your Attendance is valued.
We hit over 5k views for Spring Workshops and Updates-TY.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters, we are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
S9/This Week’s Focus:
* A continuation of Intuition-2 Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
Thx for tuning in. Your time investment is valued. I do select topics related to our timeline and community. For those seeking upgrades or Reiki Levels. Stay tuned for our June packages. It’s for self employed/Practitioners/Coaches…
Review & Topics:
* Reiki Is Japanese Energy Healing used Globally.
* Yoga is over 5k years old from India. It hosts many styles, teacher versions, and it’s Mainstream now vs decades ago.
* Anything of the Holistic, Wellness Department can be fused together. My origins are Alternative, Complementary Medicine. In short, I call this ND. I am also a metaphysician. I learnt during the 90s New Age Era. I forget we just hit another wavy. It’s GenZ word of Mouth, their New Age Era. WHOA, History Repeats lol. We are fusing together.
* So, most of you have experienced your Spiritual Awakening. However; The journey wont be perfect. There will be some roller coaster events. The perks are: We are in a faster Spiritual Zone than the 90s. There’s more support and information available.
(See Presentation for all sections, THX AGAIN.)
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfChalaKelbessa
This is Forestry Exit Exam Model for 2025 from Department of Forestry at Wollega University, Gimbi Campus.
The exam contains forestry courses such as Dendrology, Forest Seed and Nursery Establishment, Plantation Establishment and Management, Silviculture, Forest Mensuration, Forest Biometry, Agroforestry, Biodiversity Conservation, Forest Business, Forest Fore, Forest Protection, Forest Management, Wood Processing and others that are related to Forestry.
This presentation was provided by Nicole 'Nici" Pfeiffer of the Center for Open Science (COS), during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
How to Manage Maintenance Request in Odoo 18Celine George
Efficient maintenance management is crucial for keeping equipment and work centers running smoothly in any business. Odoo 18 provides a Maintenance module that helps track, schedule, and manage maintenance requests efficiently.
Available for Weekend June 6th. Uploaded Wed Evening June 4th.
Topics are unlimited and done weekly. Make sure to catch mini updates as well. TY for being here. More upcoming this summer.
A 8th FREE WORKSHOP
Reiki - Yoga
“Intuition” (Part 1)
For Personal/Professional Inner Tuning in. Also useful for future Reiki Training prerequisites. The Attunement Process. It’s all about turning on your healing skills. See More inside.
Your Attendance is valued.
Any Reiki Masters are Welcomed
More About:
The ‘Attunement’ Process.
It’s all about turning on your healing skills. Skills do vary as well. Usually our skills are Universal. They can serve reiki and any relatable Branches of Wellness.
(Remote is popular.)
Now for Intuition. It’s silent by design. We can train our intuition to be bold or louder. Intuition is instinct and the Senses. Coded in our Workshops too.
Intuition can include Psychic Science, Metaphysics, & Spiritual Practices to aid anything. It takes confidence and faith, in oneself.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course. I’m Fusing both together.
This will include the foundation of each practice. Both are challenging independently. The Free Workshops do matter. They can also be downloaded or Re-Read for review.
My Reiki-Yoga Level 1, will be updated Soon/for Summer. The cost will be affordable.
As a Guest Student,
You are now upgraded to Grad Level.
See, LDMMIA Uploads for “Student Checkin”
Again, Do Welcome or Welcome Back.
I would like to focus on the next level. More advanced topics for practical, daily, regular Reiki Practice. This can be both personal or Professional use.
Our Focus will be using our Intuition. It’s good to master our inner voice/wisdom/inner being. Our era is shifting dramatically. As our Astral/Matrix/Lower Realms are crashing; They are out of date vs 5D Life.
We will catch trickster
energies detouring us.
(See Presentation for all sections, THX AGAIN.)
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
2. Python OOPs Concepts
Like other general-purpose programming languages, Python is
also an object-oriented language since its beginning. It allows us
to develop applications using an Object-Oriented approach.
In Python, we can easily create and use classes and objects.
An object-oriented paradigm is to design the program using
classes and objects. The object is related to real-word entities such
as book, house, pencil, etc. The oops concept focuses on writing
the reusable code. It is a widespread technique to solve the
problem by creating objects.
3. Major principles of object-oriented
programming system are given below.
1. Class
2. Object
3. Method
4. Inheritance
5. Polymorphism
6. Data Abstraction
7. Encapsulation
4. Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
A class is a blueprint for the object
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
5. Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory.
Example:
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
6. The __init__() Function
All classes have a function called __init__(), which is always
executed when the class is being initiated.
Use the __init__() function to assign values to object properties,
or other operations that are necessary to do when the object is
being created:
The first argument of every method is a reference to the current
instance of the class
By convention, we name this argument self
In __init__, self refers to the object currently being created; so,
in other class methods, it
refers to the instance whose method was called Similar to the
keyword this in Java or C++.
7. Example
Create a class named Person, use the __init__() function to
assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
8. Object Methods
Example
Insert a function that prints a greeting, and execute it on the
p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
9. The self Parameter
The self parameter is a reference to the current instance of
the class, and is used to access variables that belongs to the
class.
It does not have to be named self , you can call it whatever
you like, but it has to be the first parameter of any function in
the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
10. Inheritance
Inheritance is the most important aspect of object-oriented
programming, which simulates the real-world concept of
inheritance.
It specifies that the child object acquires all the properties and
behaviors of the parent object.
By using inheritance, we can create a class which uses all the
properties and behavior of another class.
The new class is known as a derived class or child class, and
the one whose properties are acquired is known as a base class
or parent class.
It provides the re-usability of the code.
11. # parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
12. Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private attributes
using underscore as the prefix i.e single _ or double __.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
13. Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle).
However we could use the same method to color any shape. This concept is called
Polymorphism.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self): p
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
15. Files
Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard
disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the
computer is turned off), we use files for future use of the data by permanently
storing them.
When we want to read from or write to a file, we need to open it first. When we
are done, it needs to be closed so that the resources that are tied with the file are
freed.
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
16. 1 . Python File Open -
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
1. "r" - Read - Default value. Opens a file for reading, error if the file does
not exist
2. "a" - Append - Opens a file for appending, creates the file if it does not
exist
3. "w" - Write - Opens a file for writing, creates the file if it does not exist
4. "x" - Create - Creates the specified file, returns an error if the file exists
Syntax - f = open("demofile.txt")
f = open("demofile.txt", "rt")
17. Mode Description
r Opens a file for reading. (default)
w
Opens a file for writing. Creates a new file if it
does not exist or truncates the file if it exists.
x
Opens a file for exclusive creation. If the file
already exists, the operation fails.
a
Opens a file for appending at the end of the file
without truncating it. Creates a new file if it does
not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens a file for updating (reading and writing)
18. 2 . Python File Read -
1. The open() function returns a file object, which has
a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
2. If the file is located in a different location, you will have to
specify the file path, like this:
Example
f = open("D:myfileswelcome.txt", "r")
print(f.read())
3. By default the read() method returns the whole text, but
you can also specify how many characters you want to
return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
19. 3 . Python Write/Create File -
1. Write to an Existing File
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
2. Create a File
To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
20. Method Description
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating system's
perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
Built –in methods in python
21. Command Line Arguments in Python
The arguments that are given after the name of the program in the
command line shell of the operating system are known
as Command Line Arguments.
Python provides various ways of dealing with these types of
arguments.
The three most common are:
1. Using sys.argv
2. Using getopt module
3. Using argparse module
22. Using sys.argv
The sys module provides functions and variables used to
manipulate different parts of the Python runtime environment.
This module provides access to some variables used or maintained
by the interpreter and to functions that interact strongly with the
interpreter.
One such variable is sys.argv which is a simple list structure. It’s
main purpose are:
1. It is a list of command line arguments.
2. len(sys.argv) provides the number of command line arguments.
3. sys.argv[0] is the name of the current Python script.
23. # Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("nName of Python script:", sys.argv[0])
print("nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("nnResult:", Sum)
24. Using getopt module
Python getopt module is similar to the getopt() function of C.
Unlike sys module getopt module extends the separation of the input string by parameter
validation.
It allows both short, and long options including a value assignment. However, this
module requires the use of the sys module to process input data properly.
To use getopt module, it is required to remove the first element from the list of
command-line arguments.
Syntax: getopt.getopt(args, options, [long_options])
Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that
require an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that
require arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list of
(option, value) pairs. The second is the list of program arguments left after
the option list was stripped.
25. Using argparse module
Using argparse module is a better option than the
above two options as it provides a lot of options
such as positional arguments, default value for
arguments, help message, specifying data type of
argument etc.
Note: As a default optional argument, it includes
-h, along with its long version –help.