<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Python Programs</title>
	<atom:link href="https://python-programs.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://python-programs.com/</link>
	<description>Python Programs with Examples, How To Guides on Python</description>
	<lastBuildDate>Fri, 10 Nov 2023 06:54:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.5</generator>
<site xmlns="com-wordpress:feed-additions:1">196068054</site>	<item>
		<title>Python Data Persistence &#8211; @Property DGCOrator</title>
		<link>https://python-programs.com/python-data-persistence-property-dgcorator/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:13:37 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8283</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; @Property DGCOrator Although a detailed discussion on decorators is beyond the scope of this book, a brief introduction is necessary before we proceed to use @property decorator. The function is often termed a callable object. A function is also a passable object. Just as we pass a built-in object viz. number, [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-property-dgcorator/">Python Data Persistence &#8211; @Property DGCOrator</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; @Property DGCOrator</h2>
<p>Although a detailed discussion on decorators is beyond the scope of this book, a brief introduction is necessary before we proceed to use @property decorator.</p>
<p>The function is often termed a callable object. A function is also a passable object. Just as we pass a built-in object viz. number, string, list, and so on. as an argument to a function, we can define a function that receives another function as an argument. Moreover, you can have a function defined in another function (nested function), and a function whose return value is a function itself. Because of all these features, a function is called a first-order object.</p>
<p>The decorator function receives a function argument. The behavior of the argument function is then extended by wrapping it in a nested function. Definition of function subjected to decoration is preceded by name of decorator prefixed with @ symbol.<br />
Python-OOP &#8211; 113</p>
<p><strong>Example</strong></p>
<pre>def adecorator(function): 
def wrapper():
function() 
return wrapper 
@adecorator 
def decorate( ): 
pass</pre>
<p>We shall now use the property ( ) function as a decorator and define a name () method acting as a getter method for my name attribute in my class. py code above.</p>
<p><strong>Example</strong></p>
<pre>@property 
def name(self):
return self. ___myname
@property 
def age(self):
return self. __myage</pre>
<p>A property object’s getter, setter, and deleter methods are also decorators. Overloaded name ( ) and age ( ) methods are decorated with name, setter, and age. setter decorators respectively.</p>
<p><strong>Example</strong></p>
<pre>@name.setter
def name(self,name):
self. ___myname=name
@age.setter
def age(self, age):
self. myage=age</pre>
<p>When @property decorator is used, separate getter and setter methods defined previously are no longer needed. The complete code of myclass.py is as below:</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">#myclass. py
class MyClass:
__slots__=['__myname', '__myage']
def__init__(self, name=None, age=None):
self.__myname=name
self.__myage=age

@property
def name(self) :
print ('name getter method')
return self.__myname

@property
def age(self) :
print ('age getter method')
return self. ___myage

@name.setter
def name(self,name):
print ('name setter method')
self.___myname=name

@age.setter
def age(self, age):
print ('age setter method')
self.__myage=age

def about(self):
print ('My name is { } and I am { } years old'.format(self. myname,self. myage))</pre>
<p>Just import above class and test the functionality of property objects using decorators.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass('Ashok', 21)
&gt;&gt;&gt; obj1.about() #initial values of object's attributes
My name is Ashok and I, am 21 years old
&gt;&gt;&gt; #change age property
&gt;&gt;&gt; obj1.age=30
age setter method
&gt;&gt;&gt; #access name property
&gt;&gt;&gt; obj1.name
name getter method
'Ashok'
&gt; &gt; &gt; obj1.about()
My name is Ashok and I am 30 years old</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-property-dgcorator/">Python Data Persistence &#8211; @Property DGCOrator</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8283</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; property () Function</title>
		<link>https://python-programs.com/python-data-persistence-property-function/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:13:35 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8281</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; property () Function Well, let me now make a volte-face here. It’s not that Python doesn’t have private/protected access restrictions. It does have. If an instance variable is prefixed with double underscore character ‘___’, it behaves like a private variable. Let us see how: Example &#62;&#62;&#62; #private variable in class . [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-property-function/">Python Data Persistence &#8211; property () Function</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; property () Function</h2>
<p>Well, let me now make a volte-face here. It’s not that Python doesn’t have private/protected access restrictions. It does have. If an instance variable is prefixed with double underscore character ‘___’, it behaves like a private variable. Let us see how:</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; #private variable in class
. . .
&gt;&gt;&gt; class tester:
. . .             def___init___(self) :
. . .                       self.__var=10
. . .
&gt;&gt;&gt;</pre>
<p>Try .declaring an object of above class and access its__var attribute.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; t=tester( )
&gt;&gt;&gt; t.__var
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: 'tester' object has no attribute '___var'</pre>
<p>The AttributeError indicates that the variable prefixed is inaccessible. However, it can still be accessed from outside the class. A double underscore prefixed attribute is internally renamed as obj ._class var. This is called name mangling mechanism.</p>
<pre>&gt;&gt;&gt; t._tester var
10</pre>
<p>Hence, the so-called private variable in Python is not really private. However, a property object acts as an interface to the getter and setter methods of a private attribute of the Python class.<br />
Python’s built-in property() function uses getter, setter, and delete functions as arguments and returns a property object. You can retrieve as well as assign to the property as if you do with any variable. When some value is assigned to a property object, its setter method is called. Similarly, when a property object is accessed, its getter method is called.</p>
<pre>propobj=property(fget, fset, fdel, doc)</pre>
<p>In the above function signature, fget is the getter method in the class, fset is the setter method and, fdel is the delete method. The doc parameter sets the docstring of the property object.<br />
In our ongoing myclass.py script, let us now define age and name properties to interface with ___myage and ___myname private instance attributes.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">#myclass.py
class MyClass:
        __slots___= ['__myname' ,'___myage ' ]
        def__init__(self, name=None, age=None):
               self. myname =name
               self. myage=age
        def getname(self):
            print ('name getter method')
            return self. ___myname
       def setname(self, name):
           print ('name setter method')
           self. ___myname=name
      def getage(self):
           print ('age getter method')
           return self.____myage
      def setage(self, age):
           print ('age setter method') 
       self. ____myage=age
name=property(getname, setname, "Name") age=property(getage, setage, "Age") def about(self) :
print ('My name is { } and I am { } years old'.format(self.___myname,self. __myage))</pre>
<p>We’ll now import this class and use the properties. Any attempt to retrieve or change the value of property calls its corresponding getter or setter and changes the internal private variable. Note that the getter and setter methods have a print () message inserted to confirm this behavior. The about () method will also show changes in private variables due to manipulations of property objects.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass(1Ashok' , 21)
&gt;&gt;&gt; obj1.about() #initial values of object's attributes
My name is Ashok and I am 21 years old
&gt;&gt;&gt; #change age property
&gt;&gt;&gt; obj1.age=30
age setter method
&gt;&gt;&gt; #access name property
&gt;&gt;&gt; obj1.name
name getter method
'Ashok'
&gt;&gt;&gt; obj1.about( ) #object's attributes after property changes
My name is Ashok and I am 30 years old</pre>
<p>So, finally, we get the Python class to work almost similar to how the OOP methodology defines. There is a more elegant way to define property objects &#8211; by using @property decorator.</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-property-function/">Python Data Persistence &#8211; property () Function</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8281</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; Getters/setters</title>
		<link>https://python-programs.com/python-data-persistence-getters-setters/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:13:35 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8278</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; Getters/setters Java class employs getter and setter methods to regulate access to private data members in it. Let us see if it works for a Python class. Following code modifies myclass.py and provides getter and setter methods for my name and my age instance attributes. Example #myclass.py class MyClass: __slots__=['myname', 'myage'] [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-getters-setters/">Python Data Persistence &#8211; Getters/setters</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; Getters/setters</h2>
<p>Java class employs getter and setter methods to regulate access to private data members in it. Let us see if it works for a Python class. Following code modifies myclass.py and provides getter and setter methods for my name and my age instance attributes.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">#myclass.py
class MyClass:
__slots__=['myname', 'myage']
def__init__(self, name=None, age=None):
self.myname=name
self,myage=age
def getname(self):
return self.myname
def set name(self, name):
self.myname=name
def getage(self):
return self.myage
def setage(self, age):
self.myage=age
def about(self):
print ('My name is { } and I am { } years old' ,format(self.myname,self.myage) )</pre>
<p>The getters and setters allow instance attributes to be retrieved / modified.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass('Ashok',21)
&gt;&gt;&gt; obj1.getage( )
21
&gt;&gt;&gt; obj1.setname('Amar')
&gt;&gt;&gt; obj1.about( )
My name is Amar and I am 21 years old</pre>
<p>Good enough. However, this still doesn’t prevent direct access to instance attributes. Why?</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; obj1.myname
'Amar'
&gt;&gt;&gt; getattr(obj1,'myage')
21
&gt;&gt;&gt; obj1.myage=25
&gt;&gt;&gt; setattr(obj1myname1, 'Ashok')
&gt;&gt;&gt; obj1.about()
My name is Ashok and I am 25 years old</pre>
<p>Python doesn’t believe in restricting member access hence it doesn’t have access to controlling keywords such as public, private, or protected. In fact, as you can see, class members (attributes as well as methods) are public, being freely accessible from outside the class. Guido Van Rossum &#8211; who developed Python in the early 1990s &#8211; once said, “We &#8216;re all consenting adults here” justifying the absence of such access restrictions. Then what is a ‘Pythonic’ way to use getters and setters? The built-in property () function holds the answer.</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-getters-setters/">Python Data Persistence &#8211; Getters/setters</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8278</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; Constructor</title>
		<link>https://python-programs.com/python-data-persistence-constructor/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:13:28 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8273</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; Constructor We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called ‘self’. Java/C++ programmers will immediately relate this [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-constructor/">Python Data Persistence &#8211; Constructor</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; Constructor</h2>
<p>We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called ‘self’. Java/C++ programmers will immediately relate this to ‘this’ variable. A method with ‘self argument is known as an instance method. Save the following script as myclass.py. It provides two instance variables (my name and my age) and about () method.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">#myclass.py ‘
class MyClass:
            def __init__(self):
self.myname='Ashok'
self.myage=21
def about(self):
print ('My name is { } and I am { } years old'.format(self.myname,self.myage))</pre>
<p>Let us use this script as a module, import MyClass from it and have its object.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass( )
&gt; &gt; &gt; obj1.myname
'Ashok'
&gt;&gt;&gt; obj1.myage
21
&gt;&gt;&gt; obj1.about()
My name is Ashok and I am 21 years old</pre>
<p>So, now each object will have the same attributes and methods as defined in the class. However, attributes of each object will be initialized with the same values as assigned in__init__( ) method. To counter this, we can have a parameterized constructor, optionally with default values. Modify Now we can have objects having attributes with different values.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass('Ashok', 21)
&gt;&gt;&gt; obj2=MyClass('Asmita',20)
&gt;&gt;&gt; obj1.about()
My name is Ashok and I am 21 years old
&gt;&gt;&gt; obj2.about()
My name is Asmita and I am 20 years old</pre>
<p>However, does this process prevent the dynamic addition of an attribute to an object/class? Well, not really.</p>
<pre>&gt;&gt;&gt; setattr(obj1marks50)
&gt;&gt;&gt; obj1.marks
50

</pre>
<p>So, how do we ensure that the object will have only those attributes as per the class definition? The answer is slots .</p>
<p><strong>_slots_</strong></p>
<p>To prevent any further attribute to be added to an object of a class, it carries a variable named as<strong>__slots__</strong>. This variable is defined before__init__ () method. It is a list of allowed attributes to be initialized by the constructor. The setattr () function will first check if the second argument is in the<strong>__slots__</strong>list and assign it a new value only if it exists.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">#myclass.py
class MyClass:
          __slots___=['myname', 'myage']
         def__init___(self, name=None, age=None):
                 self.myname=name
                 self.myage=age
def about(self):
               print ('My name is { } and I am { } years old1.format(self.myname,self.myage))</pre>
<p>Import the modified class and check the effect of__slots___variable.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass('Ashok', 21)
&gt; &gt; &gt; obj1.about( )
My name is Ashok and I am 21 years old
&gt;&gt;&gt; setattr(obj1, 'marks', 50) #new attribute not allowed
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: 'MyClass' object has no attribute 'marks'
&gt;&gt;&gt; setattr(obj1, 'myage', 25) #value of existing module can be modified
&gt;&gt;&gt; obj1.about()
My name is Ashok and I am 25 years old</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-constructor/">Python Data Persistence &#8211; Constructor</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8273</post-id>	</item>
		<item>
		<title>Python Data Persistence object-oriented programming</title>
		<link>https://python-programs.com/python-data-persistence-object-oriented-programming/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:13:15 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8263</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; OOP The object-oriented programming paradigm has emerged as a cornerstone of modern software development. Python too is a predominantly object-oriented language, although it supports classical procedural approach also. Python’s implementation of OOP is a little different from that of C++ and Java, and is in keeping with ‘Simple is better than [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-object-oriented-programming/">Python Data Persistence object-oriented programming</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; OOP</h2>
<p>The object-oriented programming paradigm has emerged as a cornerstone of modern software development. Python too is a predominantly object-oriented language, although it supports classical procedural approach also. Python’s implementation of OOP is a little different from that of C++ and Java, and is in keeping with ‘Simple is better than Complex’ &#8211; one of the design principles of Python. Let us not go into much of the theory of object-oriented programming methodology and its advantages. Instead, let us dive straight into Python’s brand of OOP!</p>
<p>Everything in Python is an object. This statement has appeared more than once in previous chapters. What is an object though? Simply put, object is a piece of data that has a tangible representation in computer’s memory. Each object is characterized by attributes and behaviour as stipulated in a template definition called class. In Python, each instance of any data type is an object representing a certain class. Python’s built-in type ( ) function tells you to which class an object belongs to. (figure 4.1)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; num=1234
&gt;&gt;&gt; type(num)
&lt;class 'int'&gt;
&gt;&gt;&gt; complexnum=2+3j
&gt;&gt;&gt; type(complexnum)
&lt;class 'complex'&gt;
&gt;&gt;&gt; prices={ 'pen' :50, 'book' :200}
&gt;&gt;&gt; type(prices)
&lt;class 'diet'&gt;
&gt;&gt;&gt;</pre>
<p>Each Python object also possesses an attribute__class__that returns class. (figure 4.2)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; num.__class__
&lt;class 'int'&gt;
&gt;&gt;&gt; complexnum.__class__
&lt;class 'complex'&gt;
&gt;&gt;&gt; prices.__class__
&lt;class 'diet'&gt;
&gt;&gt;&gt;</pre>
<p>Hence, it is clear that num is an object of int class, a complexion is an object of the complex class, and so on. As mentioned above, an object possesses attributes (also called data descriptors) and methods as defined in its respective class. For example, the complex class defines real and image attributes that return the real and imaginary parts of a complex number object. It also has conjugate () method returning a complex number with the imaginary part of the opposite sign, (figure 4.3)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; complexnum=2+3j
&gt;&gt;&gt; #attr.ibutes
. . .
&gt;&gt;&gt; complexnum.real
2.0
&gt;&gt;&gt; complexnum.imag
3.0
&gt;&gt;&gt; #method
. . .
&gt;&gt;&gt; complexnum.conjugate()
(2-3j )</pre>
<p>In the above example, real and imag are the instance attributes as their values will be different for each object of the complex class. Also, the conjugate 0 method is an instance method. A class can also have class-level attributes and methods which are shared by all objects. We shall soon come across their examples in this chapter.</p>
<p>Built-in data types in Python represent classes defined in the builtins module. This module gets loaded automatically every time when the interpreter starts. The class hierarchy starts with object class. The builtins module also defines Exception and built-in functions (many of which we have come across in previous chapters).</p>
<p>The following diagram rightly suggests that built-in classes (int, float, complex, bool, list, tuple, and diet) are inherited from the object class. Inheritance incidentally is one of the characteristic features of Object-Oriented Programming Methodology. The base attribute of each of these classes will confirm this.</p>
<p>Python’s built-in function library also has issubclass ( ) function to test if a certain class is inherited from another. We can use this function and confirm that all built-in classes are sub-classes of the object classes. Interestingly, class is also an object in Python. Another built-in function is±nstance() returns True if the first argument is an object of the second argument which has to be a class. By the way, type ( ) of any built-in class returns type which happens to be a metaclass of which all classes are objects, is itself a subclass of the object as its base class, (figure 4.4)</p>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-8265" src="https://python-programs.com/wp-content/uploads/2021/06/Python-Data-Presistence-OOP-chapter-4-img-1.png" alt="Python Data Presistence - OOP chapter 4 img 1" width="262" height="537" srcset="https://python-programs.com/wp-content/uploads/2021/06/Python-Data-Presistence-OOP-chapter-4-img-1.png 262w, https://python-programs.com/wp-content/uploads/2021/06/Python-Data-Presistence-OOP-chapter-4-img-1-146x300.png 146w" sizes="(max-width: 262px) 100vw, 262px" /></p>
<p>Following interpreter, activity shows that bool class is derived from int class, which is a subclass of object class and also an object of object class!</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; isinstance(int, object)
True
&gt;&gt;&gt; issubclass(bool, int)
True
&gt;&gt;&gt; int. bases
(&lt;class 'object'&gt;,)
&gt;&gt;&gt; isinstance(int, object)
True</pre>
<p>Each class also has access to another attribute__mro__(method resolution order) which can show the class hierarchy of inheritance. The bool class is inherited from int and int from the object.</p>
<p><strong>Example</strong></p>
<pre>&gt;&gt;&gt; bool.__mro__
(&lt;class 'boo'&gt;, &lt;class 'int'&gt;, &lt;class 'object'&gt;)</pre>
<p>As mentioned above, type () on any built-in class returns type class which in turn is both a subclass and instance of the object class.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; type(bool)
&lt;class 'type'&gt;
&gt;&gt;&gt; type.__bases__
(&lt;class 'object'&gt;,)
&gt;&gt;&gt; isinstance(type, object)
True
&gt;&gt;&gt; issubclass(type, object)
True</pre>
<p>Other important constituents of Python program such as functions or modules are also objects, as the following interpreter activity demonstrates:</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; #function from a module
. . .
&gt;&gt;&gt; import math
&gt;&gt;&gt; type(math.sqrt)
&lt;class 'builtin_function_or_method'&gt;
&gt;&gt;&gt; #built-in function
. . .
&gt;&gt;&gt; type(id)
cclass 'builtin_function_or_method'&gt;
&gt;&gt;&gt; #user defined function
. . .
&gt;&gt;&gt; def hello( ):
... print ('Hello World')
. . .
&gt;&gt;&gt; type(hello)
&lt;class 'function'&gt;
&gt;&gt;&gt; #module is also an object
. . .
&gt;&gt;&gt; type(math)
&lt;class 'module'&gt;</pre>
<p>We have used the range ( ) function in connection with for loop. It actually returns a range object which belongs to the range class.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; #range is also an object
. . .
&gt;&gt;&gt; obj=range(10)
&gt;&gt;&gt;type(obj)
&lt;class 'range'&gt;
&gt;&gt;&gt; &gt;&gt;&gt; range._bases__
(&lt;class 'object'&gt;,)</pre>
<p>The post <a href="https://python-programs.com/python-data-persistence-object-oriented-programming/">Python Data Persistence object-oriented programming</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8263</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; Exceptions</title>
		<link>https://python-programs.com/python-data-persistence-exceptions/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:12:46 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8356</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; Exceptions Even an experienced programmer’s code does contain errors. If errors pertain to violation of language syntax, more often than not, they are detected by the interpreter (compiler in case of C++/Java) and code doesn’t execute till they are corrected. There are times though when the code doesn’t show syntax-related errors [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-exceptions/">Python Data Persistence &#8211; Exceptions</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; Exceptions</h2>
<p>Even an experienced programmer’s code does contain errors. If errors pertain to violation of language syntax, more often than not, they are detected by the interpreter (compiler in case of C++/Java) and code doesn’t execute till they are corrected.</p>
<p>There are times though when the code doesn’t show syntax-related errors but errors creep up after running it. What is more, sometimes code might execute without errors and some other times, its execution abruptly terminates. Clearly, some situation that arises in a running code is not tolerable to the interpreter. Such a runtime situation causing the error is called an exception.<br />
Take a simple example of displaying the result of two numbers input by the user. The following snippet appears error-free as far as syntax error is concerned.</p>
<p><strong>Example</strong></p>
<pre>num1=int(input('enter a number..')) 
num2 = int(input(1 enter another number..')) 
result=num1/num2 
print ('result: ' , result)</pre>
<p>When executed, above code gives satisfactory output on most occasions, but when num2 happens to be 0, it breaks, (figure 5.3)</p>
<pre>enter a number . . 12
enter another number . . 3
result: 4.0
enter a number . . 12
enter another number . . 0
Traceback (most recent call last) :
File "E:\python37\tmp.py", line 3, in &lt;module&gt; 
result =num1/num2
ZeroDivisionError: division by zero</pre>
<p>You can see that the program terminates as soon as it encounters the error without completing the rest of the statements. Such abnormal termination may prove to be harmful in some cases.<br />
Imagine a situation involving a file object. If such runtime error occurs after the file is opened, the abrupt end of the program will not give a chance for the file object to close properly and it may result in corruption of data in the file. Hence exceptions need to be properly handled so that program ends safely.</p>
<p>If we look at the class structure of builtins in Python, there is an <strong>Exception</strong> class from which a number of built-in exceptions are defined. Depending upon the cause of exception in a running program, the object representing the corresponding exception class is created. In this section, we restrict ourselves to consider file operations-related exceptions.</p>
<p>Python’s exception handling mechanism is implemented by the use of two keywords <strong>&#8211; try</strong> and except. Both keywords are followed by a block of statements. The <strong>try:</strong> block contains a piece of code that is likely to encounter an exception. The<strong> except</strong> block follows the <strong>try:</strong> block containing statements meant to handle the exception. The above code snippet of the division of two numbers is rewritten to use the try-catch mechanism.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">try:
num1=int(input('enter a number..'))
num2=int(input('enter another number..'))
result=num1/num2
print (' result: ' , result)
except:
print ("error in division")
print ("end of program")</pre>
<p>Now there are two possibilities. As said earlier, the exception is a runtime situation largely depending upon reasons outside the program. In the code involving the division of two numbers, there is no exception if the denominator is non-zero. In such a case, try: block is executed completely, except block is bypassed and the program proceeds to subsequent statements.</p>
<p>If however, the denominator happens to be zero, a statement involving division produces an exception. Python interpreter abandons rest of statements in try: block and sends the program flow to except: block where exception handling statements are given. After except: block rest of unconditional statements keep on executing, (figure 5.4)</p>
<pre>enter a number..15 
enter another number..5 
result: 3.0
end of program 
enter a number..15 
enter another number..0 
error in division 
end of program</pre>
<p>Here, except block without any expression acts as a generic exception handler. To catch objects of a specific type of exception, the corresponding Exception class is mentioned in front of except keyword. In this case, ZeroDivisionError is raised, so it is mentioned in except statement. Also, you can use the ‘as’ keyword to receive the exception object in an argument and fetch more information about the exception.</p>
<p><strong>Example</strong></p>
<pre>try:
num1=int(input('enter a number..')) 
num2=int(input('enter another number..')) 
result =num1/num2 
print ('result: ', result) 
except ZeroDivisionError as e: 
print ("error message",e) 
print ("end of program")</pre>
<p>File operations are always prone to raising exceptions. What if the file you are trying to open doesn’t exist at all? What if you opened a file in ‘r’ mode but trying to write data to it? These situations will raise runtime errors (exceptions) which must be handled using the try-except mechanism to avoid damage to data in files.<br />
FileNotFoundError is a common exception encountered. It appears when an attempt to read a non-existing file. The following code handles the error.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">E:\python37&gt;python tmp.py
enter a filename, .testfile.txt
H e l l o P y t h o n
end of program
E:\python37&gt;python tmp.py
enter filename, .nofile.txt
error message [Errno 2] No such file or directory:
' nofile . txt '
end of program</pre>
<p>Another exception occurs frequently when you try to write data in a file opened with ‘r’ mode. Type of exception is UnsupportedOperation defined in the io module.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import io
try:
f=open ( ' testfile . txt1 , ' r ')
f.write('Hello')
print (data)
except io.UnsupportedOperation as e:
print ("error message",e)
print ("end of program")</pre>
<p><strong>Output</strong></p>
<pre>E:\python37 &gt;python tmp.py 
error message not writable 
end of program</pre>
<p>As we know, the write ( ) method of file objects needs a string argument. Hence the argument of any other type will result in typeError.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">try:
f=open (' testfile . txt' , ' w')
f.write(1234)
except TypeError as e:
print ("error message",e)
print ("end of program")</pre>
<p>&nbsp;</p>
<p><strong>Output</strong></p>
<pre>E:\python37&gt;python tmp.py
error message write() argument must be str, not int end of program</pre>
<p>Conversely, for file in binary mode, the<strong> write ()</strong> method needs bytes object as argument. If not, same TypeError is raised with different error message.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">try:
f =open ( ' testfile . txt' , ' wb' )
f.write('Hello1)
except TypeError as e:
print ("error message",e)
print ("end of program")</pre>
<p><strong>Output</strong></p>
<pre>E:\python37&gt;python tmp.py
error message a bytes-like object is required, not 'str'
end of program</pre>
<p>All file-related functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os
try:
fd=os . open ( ' testfile . txt' , os . 0_RD0NLY | os . 0_CREAT) os.write(fd,'Hello'.encode())
except OSError as e:
print ("error message",e)
print ("end of program")</pre>
<p><strong>Output</strong></p>
<pre>E:\python37&gt;python tmp.py
error message [Errno 9] Bad file descriptor 
end of program</pre>
<p>In this chapter, we learned the basic file handling techniques. In the next chapter, we deal with advanced data serialization techniques and special-purpose file storage formats using Python’s built-in modules.</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-exceptions/">Python Data Persistence &#8211; Exceptions</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8356</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; File/Directory Management Functions</title>
		<link>https://python-programs.com/python-data-persistence-file-directory-management-functions/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:12:34 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8354</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; File/Directory Management Functions We normally use operating systemâ€™s GUI utilities or DOS commands to manage directories, copy, and move files etc. The os module provides useful functions to perform these tasks programmatically. os .mkdir ( ) function creates a new directory at given path. The path argument may be absolute or [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-file-directory-management-functions/">Python Data Persistence &#8211; File/Directory Management Functions</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; File/Directory Management Functions</h2>
<p>We normally use operating systemâ€<img src="https://s.w.org/images/core/emoji/15.0.3/72x72/2122.png" alt="™" class="wp-smiley" style="height: 1em; max-height: 1em;" />s GUI utilities or DOS commands to manage directories, copy, and move files etc. The <strong>os</strong> module provides useful functions to perform these tasks programmatically.<strong> os .mkdir ( )</strong> function creates a new directory at given path. The path argument may be absolute or relative to the current directory. Use<strong> chdir ( )</strong> function to set current working directory at the desired path. The <strong>getcwd ( )</strong> function returns the current working directory path.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; os.mkdir('mydir')
&gt;&gt;&gt; os.path.abspath('mydir')
'E:\\python37\\mydir'
&gt;&gt;&gt; os.chdir('mydir')
&gt;&gt;&gt; os.getcwd()
'E:\\python37\\mydir'</pre>
<p>You can remove a directory only if the given path to<strong> rmdir ( )</strong> function is not the current working directory path, and it is empty.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; os.chdir( ' . . ' ) #parent directory becomes current working directory
&gt;&gt;&gt; os.getcwd ( )
'E:\\python37'
&gt;&gt;&gt; os.rmdir('mydir')</pre>
<p>The <strong>rename ( )</strong> and <strong>remove ( )</strong> functions respectively change the name of a file and delete a file. Another utility function is<strong> listdir ()</strong> which returns a list object comprising of file and subdirectory names in a given path.</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-file-directory-management-functions/">Python Data Persistence &#8211; File/Directory Management Functions</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8354</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211;  File Handling using os Module</title>
		<link>https://python-programs.com/python-data-persistence-file-handling-using-os-module/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:12:31 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8350</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; File Handling using os Module Python’s built-in library has an os module that provides useful operating system-dependent functions. It also provides functions for performing low-level read/write operations on the file. Let us briefly get acquainted with them. The open () function from the os module (obviously it needs to be referred [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-file-handling-using-os-module/">Python Data Persistence &#8211;  File Handling using os Module</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; File Handling using os Module</h2>
<p>Python’s built-in library has an os module that provides useful operating system-dependent functions. It also provides functions for performing low-level read/write operations on the file. Let us briefly get acquainted with them.</p>
<p>The <strong>open ()</strong> function from the os module (obviously it needs to be referred to as <strong>os. open ( ))</strong> is similar to the built-in <strong>open ( )</strong> function in the sense it also opens a file for reading/write operations. However, it doesn’t return a file or file-like object but a file descriptor, an integer corresponding to the file opened. File descriptor’s values 0, 1, and 2 are reserved for <strong>stdin,</strong> <strong>stout</strong>, <strong>and stder r</strong> streams. Other files will be given an incremental file descriptor. Also, the<strong> write ( )</strong> and <strong>read( )</strong> functions of the os module needs bytes to object as the argument. The <strong>os .open ()</strong> function needs to be provided one or combinations of the following constants: (Table 5.2)</p>
<table>
<tbody>
<tr>
<td width="126">os.OWRONLY</td>
<td width="198">open for writing only</td>
</tr>
<tr>
<td width="126">os.ORDWR</td>
<td width="198">open for reading and writing</td>
</tr>
<tr>
<td width="126">os.OAPPEND</td>
<td width="198">append on each write</td>
</tr>
<tr>
<td width="126">os.OCREAT</td>
<td width="198">create file if it does not exist</td>
</tr>
<tr>
<td width="126">os.OTRUNC</td>
<td width="198">truncate size to 0</td>
</tr>
<tr>
<td width="126">os.OEXCL</td>
<td width="198">error if create and file exists</td>
</tr>
</tbody>
</table>
<p>As in the case of a file object, the os module defines a <strong>sleek ()</strong> function to set file r/w position at the desired place from the beginning, current position, or end indicated by integers 0,1, and 2 respectively.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; fd=os . open ("testfile. txt", os .0_RDWR | os .0_CREAT)
&gt;&gt;&gt; text="Hello Python"
&gt;&gt;&gt; encoded=text.encode(encoding='utf-16')
&gt;&gt;&gt; os.write(fd, encoded)
&gt;&gt;&gt; os.lseek(fd,0,0)
&gt;&gt;&gt; encoded=os.read(fd)
&gt;&gt;&gt; os.path.getsizeCtestfile.txt") #calculate file size
&gt;&gt;&gt; encoded=os.read(fd, 26)
&gt;&gt;&gt; text=encoded.decode('utf-16 ')
&gt;&gt;&gt; text
'Hello Python'</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-file-handling-using-os-module/">Python Data Persistence &#8211;  File Handling using os Module</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8350</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; Simultaneous Read/Write</title>
		<link>https://python-programs.com/python-data-persistence-simultaneous-read-write/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:12:28 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8348</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; Simultaneous Read/Write Modes ‘w’ or ‘a’ allow a file to be written to, but not to be read from. Similarly, ‘r’ mode facilitates reading a file but prohibits writing data to it. To be able to perform both read/write operations on a file without closing it, add the ‘+’ sign to [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-simultaneous-read-write/">Python Data Persistence &#8211; Simultaneous Read/Write</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; Simultaneous Read/Write</h2>
<p>Modes ‘w’ or ‘a’ allow a file to be written to, but not to be read from. Similarly, ‘r’ mode facilitates reading a file but prohibits writing data to it. To be able to perform both read/write operations on a file without closing it, add the ‘+’ sign to these mode characters. As a result <strong>‘w+’, ‘r+’</strong> or <strong>‘a+’</strong> mode will open the file for simultaneous read/write. Similarly, binary read/ write simultaneous operations are enabled on file if opened with <strong>‘wb+’, ‘rb+’</strong> or <strong>‘ab+’</strong> modes.</p>
<p>It is also possible to perform read or write operations at any byte position of the file. As you go on writing data in a file, the<strong> end of file (EOF)</strong> position keeps on moving away from its beginning. By default, new data is written at the current EOF position. When opened in ‘r’ mode, reading starts from the 0th byte i.e. from the beginning of the file.<br />
The <strong>seek ( )</strong> method of file object lets you set current reading or writing position to a desired byte position in the file. It locates the desired position by counting the offset distance from beginning (0), current position (1), or EOF (2). Following example illustrates this point:</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; file=open ("testfile . txt", "w+")
&gt;&gt;&gt; file .write ("This is a rat race")
&gt;&gt;&gt; file.seek(10,0) #seek 10th byte from beginning
&gt;&gt;&gt; txt=file . read (3) #read next 3 bytes
&gt;&gt;&gt; txt
' rat'
&gt;&gt;&gt; file . seek (10,0) #seek 10th byte position
&gt;&gt;&gt; file . write ('cat' ) #overwrite next 3 bytes
&gt;&gt;&gt; file.seek(0)
&gt;&gt;&gt; text=file . read () #read entire file
&gt;&gt;&gt; text
'This is a cat race'
&gt;&gt;&gt; file . close ( )</pre>
<p>Of course, this may not work correctly if you try to insert new data as it may overwrite part of existing data. One solution could be to read the entire content in a memory variable, modify it, and rewrite it after truncating the existing file. Other built-in modules like file input and map allow modifying files in place. However, later in this book, we are going to discuss a more sophisticated tool for manipulating databases and update data on a random basis.</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-simultaneous-read-write/">Python Data Persistence &#8211; Simultaneous Read/Write</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8348</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; Write/Read Binary File</title>
		<link>https://python-programs.com/python-data-persistence-write-read-binary-file/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:12:20 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8343</guid>

					<description><![CDATA[<p>Python Data Persistence &#8211; Write/Read Binary File When the mode parameter to open ( ) function is set to ‘w’ (or ‘a’) value, the file is prepared for writing data in text format. Hence write ( ) and writelines () methods send string data to the output file stream. The file is easily readable using [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-write-read-binary-file/">Python Data Persistence &#8211; Write/Read Binary File</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; Write/Read Binary File</h2>
<p>When the mode parameter to <strong>open ( )</strong> function is set to <strong>‘w’</strong> (or ‘a’) value, the file is prepared for writing data in text format. Hence<strong> write ( )</strong> and<strong> writelines ()</strong> methods send string data to the output file stream. The file is easily readable using any text editor. However, other computer files that represent pictures (.jpg), multimedia (.mp3, .mp4), executables (.exe, .com), databases (.db, .sqlite) will not be readable if opened using notepad like text editor because they contain data in binary format.</p>
<p>Python’s <strong>open( )</strong> function lets you write binary data to a file. You need to add <strong>‘b’</strong> to the mode parameter. Set mode to <strong>‘wb’</strong> to open a file for writing binary data. Naturally, such a file needs to be read by specifying <strong>‘rb’</strong> as file opening mode.</p>
<p>In the case of<strong> ‘wb’</strong> mode parameter, the write () method doesn’t accept a string as an argument. Instead, it requires a bytes object. So, even if you are writing a string to a binary file, it needs to be converted to bytes first. The <strong>encode ( )</strong> method of string class converts a string to bytes using one of the defined encoding schemes, such as <strong>‘utf-8’</strong> or <strong>‘utf-16’.</strong></p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; f=open('binary.dat' , 'wb')
&gt;&gt;&gt; data='Hello Python'
&gt;&gt;&gt; encoded=data.encode(encoding='utf-16')
&gt;&gt;&gt; encoded
b'\xff\xfeH\x00e\x001\x001\x00o\x00 \x00P\x00y\x00t\ x00h\x00o\x00n\x00'
&gt;&gt;&gt; f.write(encoded)
26
&gt;&gt;&gt; f.close( )</pre>
<p>To read back data from the binary files, the encoded strings will have to be decoded for them to be used normally, like printing it.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt; &gt; &gt; f=open('binary.dat', 'rb')
&gt;&gt;&gt; encoded=f.read( )
&gt;&gt;&gt; data=encoded.decode(encoding='utf-16')
&gt;&gt;&gt; print (data)
Hello Python
&gt;&gt;&gt; f.close( )</pre>
<p>If you have to write numeric data to a binary file, number object is first converted to bytes and then provided as argument to write() method</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; f=open('binary.dat','wb')
&gt;&gt;&gt; num=1234
&gt;&gt;&gt; binl=num.to_bytes(16, 'big')
&gt;&gt;&gt; f.write(bin1)
&gt;&gt;&gt; f.close( )</pre>
<p>To read integer data from binary file, it has to be extracted from bytes in the file.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; f=open( ' binary.dat' , 'rb')
&gt;&gt;&gt; data=f.read( )
&gt;&gt;&gt; num=int.from_bytes(data,'big')
&gt; &gt; &gt; num
1234
&gt;&gt;&gt; f.close( )</pre>
<p>In the <strong>to_bytes ()</strong> and <strong>from_bytes ()</strong> function, <strong>‘big’</strong> is the value of the byte order parameter. Writing float data to a binary file is a little complicated. You’ll need to use the built-in struct module and <strong>pack( )</strong> function from it to convert float to binary. Explanation of struct module is beyond the scope of this book.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; import struct
&gt; &gt; &gt; numl=1234.56
&gt;&gt;&gt; f=open('binary.dat','wb')
&gt;&gt;&gt; binfloat = struct .pack ('f ' num1)
&gt; &gt; &gt; f . write (binfloat)
4
&gt; &gt; &gt; f.close ( )</pre>
<p>To read back binary float data from file, use unpack () function.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; f=open('binary.dat','rb')
&gt;&gt;&gt; data=f.read( )
&gt;&gt;&gt; numl=struct.unpack('f', data)
&gt;&gt;&gt; print (num1)
(1234.56005859375,)
&gt;&gt;&gt; f.close( )</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-data-persistence-write-read-binary-file/">Python Data Persistence &#8211; Write/Read Binary File</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8343</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: python-programs.com @ 2026-04-06 17:57:18 by W3 Total Cache
-->