files, Object Storage and type conversion of python with example

files, Object Storage and type conversion of python with example

Files

Python’s access to files is built into Python in the same way as the other object types you’ve already seen. You create a file object by using the built-in open function, and then you use methods on the new object to read and write information to and from the file. This eliminates a lot of the complexity of the file handle model used by C, Perl, and VB; instead, you get a consistent interface to what is essentially just another form of storage available on your machine.

We won’t look at the specifics of using files for the moment; we’ll leave that to Chapter 11 when you’ll learn how to use Python for processing and managing files. However, to get a taste, look at the following script that opens and reads each line from the file myfile.txt before displaying the lines to the screen:

input = open('myfile.txt')

for line in input.readlines ():

print line

input.close()

Object Storage

Although Python always creates objects when you create a variable, it’s important to understand the association between the name, the object, and the variable. At the risk of sounding like a stuck record, we’ll reiterate again the statement we made at the beginning of this chapter. Python stores information as objects. In truth, Python actually stores references or pointers to the internal structures used to store the information for a specific object type. This is the equivalent of the C pointer or the Perl reference a Python object is merely the address of a structure stored in memory.

With C, to introduce a special variable into your application you have to use either a pointer to a structure or predefine a structure before you use the data type. Using pointers, while practical at a system level, is difficult and adds extra layers of complexity that you don’t need. In addition, the programmer needs to be aware that the variable they’re dealing with is a pointer and therefore requires special treatment.

With Perl, the programmer has to make a conscious effort to use a reference as a specific data type. You must dereference a Perl reference before you can access the information. If you don’t dereference or you dereference to the wrong type (i.e., try to access a hash as a scalar), you get either the physical address of the variable or an error during compilation. This problem is easy to spot, but it adds extra complication to the programming process that frankly you could do without.

Unlike Perl and C however, the Python programmer never needs to be aware of the fact that the pointers exist. When you access an object, you are accessing the information stored in it, irrespective of how the object is defined or where or how the object information is actually stored.

Objects, Names, and Variables

The Python name is the alphanumeric name given to the pointer that points to the object. Note the following example:

greeting = 'Hello World'

In the preceding statement, the name is greeting. The object has no identifiable name; it’s just an allocated patch of memory which is pointed to by greeting. But the object’s type is a string. The combination of the two can be thought of as a typical variable. The significance of the pointer is important. Consider what happens when you reassign the value of the variable:

greeting = ['Hello" , "World']

The name has remained the same, but the object to which it points is in a different physical location within memory, and is of a completely different type.

Variable Name Rules

Python follows some very basic rules for naming variables.

•Variables must begin with an underscore or a letter, and they may contain any combination of letters, digits, or underscores. You cannot use any other punctuation characters.

•Variables are case sensitive-string and String are two different variable names.

•Reserved words cannot be superceded by variables. The full list of reserved words is as follows:

andassertbreakclasscontinue
defdelelifelseexcept
execfinallyforfromglobal
ifimportinislambda
notorpassprintraise
returntrywhile

Because Python is case sensitive, there is no reason why you cannot have variables called Return and RETURN, although it’s probably a bad idea.

Python Copies References, Not Data

When you refer to a Python object by name when assigning information to an object, Python stores the reference, not the data. For example, the following code appears to create two objects:

objects = [1, 2, 3]

objectb = objecta

In fact, you have only created one object but you have created two names (pointers) to that object, as demonstrated by trying the statements interactively:

>>> objecta = [1,2,3]

>>> objectb = objecta

>>> objecta[1]= 4

>>>print objectb

[1, 4, 3]

To create a copy of an object you must force Python to explicitly assign either the value of the object or you can use one of the type converters described shortly. The former method is often the easiest with lists and tuples:

Objectb = objecta[ : ]

The effects of copying the pointer to the object rather than copying the contents of the object pose some interesting possibilities. Most useful of all is the fact that because this is Python’s normal behavior, building complex structures becomes a natural rather that a forced process. For example, you can use objects to specify the keys used for dictionaries. You can build a list of tables for your contacts database like this:

Tables = { contacts : ' A list of contents' ,
           addresses : ' The address list' }

It doesn’t matter if the contents of contacts change because the key specified in the tables dictionary is just a pointer to the contacts object, it’s not a copy of the contacts dictionary.

Nesting

Because Python copies object pointers, you can use objects anywhere; you are not limited to the normal boundaries and restrictions placed on variables in other languages. For example, you have already seen that a list can contain a mixture of strings and numbers and even other lists. For example, the following structure describes a list of contacts using a combination of lists and dictionaries to describe the information:

Contacts = [{' Name ' : 'Martin' ,
                     ' Email, :  '[email protected]'},
                    {' Name' : 'bob' ,
                      ' Email, : '[email protected]'}]

Part 3 of this book contains more examples of nesting as you start to learn in more detail how you can use Python to solve specific problems.

Type Conversion

Beyond the methods and operators already discussed for the individual object types, there are a number of built-in functions that can convert data from one type to another. Table 3-11 contains the full list of such functions.

There is also a special operator supported by Python that works in the same way as the str()) built-in function. The” (back ticks) operator evaluates the enclosed statement and then returns a string representation, as in the following example:

>>> Print ' (34*56.0)'
1904
>>> albem = (' TMBG' , 'Flood' , 'Them flood' , 'birdhouse in your soul' )
>>> 'albem[:2]'
"('TMBG' , 'Flood' )"
>>> Str(albem[:2])
"('TMBG' , 'Flood' )"
>>> 'list(albem)'
"[ 'TMBG' , 'Flood' , 'Theme from flood' , 'Birdhouse in your soul' ]"

Note that the format used by both str and “when returning the information is the same as would be required to build the object. Therefore, to display the Python statements required to build the earlier album list, use the following statement:

Contacts = [{ 'Name' : 'Sohail' ,
                    'Email ' : '[email protected]'},
                    {'Name' : 'bob',
                    'Email' : '[email protected]'}]
>>> >>>`contacts`
" [{'Email' : [email protected]', 'name' : 'martin}, {' Email ': '[email protected]', 'Name' : 'bob' }]"
FunctionDescription
str()Translates the object x into a string.
list(x)Returns the sequence object x as a list. For example, the string “hello” is returned as [`h`,`e`,`i,`o`]. Converts tuples and lists to lists.
tuple(x)Returns the sequence object x as a tuple.
int(x)Converts a string or number to an integer. note that floating-point numbers are truncated, not rounded; int(3.6) becomes 3.
long(x)Converts a string or number to a long integer. Conversion as for int.
float(x)Converts a string or number to a floating- point object.
complex(x,y)Creates a complex number with real part of x and imaginary part of y.
hex(x)Converts an integer or long to a hexadecimal string.
oct(x)converts an integer or long to an octal string.
ord(x)Returns the ASCII value for the character x.
chr(x)Returns the character (as a string) for the ASCII code x.
min(x[, …])Returns the smallest element of a sequence.
max(x[, …])Returns the largest element of a sequence.
table 3-11. Built Type conversions

Type Comparisons

When you compare two objects within Python, the interpreter compares the values of both objects before returning the result of the comparison. This means that when your compare two lists, the contents of both lists are examined to determine whether they are identical. The same is true of all other object tests-the interpreter checks the contents of each data structure when making the comparison.

Table 3-12 lists the supported operators for type comparisons.


There are some special cases shown in Table 3-12. If you create two identical lists and compare their values, you should get a return value of 1, to indicate that the two lists are of equal value.

>> lista = [1, 2, 3]

>>> listb = [1, 2, 3]

>>> linta = list

1

Note as well that the order as well as the values is important: 

>>> listb = [2, 3, 1]

>>> lista == listb

0

OperatorDescription
x<yLess than.
x<=y Less than or equal to.
x> yGreater than.
x>=yGreater than or equal to.
x==yHave equal value.
x!=y,x<>yDo not have equal value.
x is yPointers to same object.
x is not y Different objects.
Not yInverse-returns true if x is false /false if x is true.
x or yReturns x if x is true, or y if x is false.
x and y Returns x if x is false, or y if x is true.
x<y<zChained comparisons; returns true only if all operators return true.

    Table 3-12. Comparison Operators


To compare whether the two objects are identical, eg, that they both point to the same physical object, you need to compare the two objects using the is operator:

>>> lista is listb

0

You need to use the is operator because there are two separate objects. Copying the object reference from lista to listb however

>>> listb = lista

>>> lista is listb 

1

Give us the result you expect. 

The is operator is useful when you want to check the source and validity of a object against a source or control object. 

Python makes its comparisons using the following rules:-

•Numbers are compared by magnitude.

•Strings are compared character by character.

•Lists and tuples are compared by element, from the lowest to highest index.

•Dictionaries are compared by comparing sorted key/value pairs.

All comparisons within Python return I if the result is true, or 0 if the comparison fails. In addition, Python treats any non-zero value as true, including a string. The only exceptions to this rule are None, which is false, and any empty object (list, tuple, or sequence). Table 3-13 contains a summary of the different true/false values.

Object/ConstantValue
False
‘string’True
0False
>1True
<-1True
()(empty Tuple)False
[ ](empty list)False
{ }( empty distionary)False
NoneFalse
Table 3-13. True/False Values of objects and constants

Conclusion:-

This post has become quite big, I will tell in the next post that , statement, statement format, control statements, etc. in python. How do they work and how do you use them?

Note:- How did you like this post, do tell by commenting below. 

Previous articlejava language syllabus(history of java language)
Next articleWhat is a statement in Python-sirf padhai

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here