Tuesday, July 28, 2015

File Handling Best Practices

File Handling Best Practices:

>>>fp = open('testfl.txt','r+') # Opens a file in read and write mode
>>> fp.read()  # read all contents of the file
'My first line\n'
>>> fp.seek(0) # changes the position of fp to 0
>>> fp.read(1)  # Read one byte from file
'M'
>>> fp.read(2)
'y '
>>> fp.flush()  # Always Best Practice to use flush when changing from read to write operation or from vice versa.

>>> fp.seek(0)
>>> fp.seek(16)
>>> fp.tell()
16L
>>> fp.write('My Second Line\n')
>>> fp.flush()
>>> fp.read()
''
>>> fp.tell()
32L
>>> fp.seek(0)
>>> fp.read()
'My first line\n\x00My Second Line\n'
>>> fp.seek(0)

>>> for line in fp:
print line

My first line

 My Second line

>>> fp.close()   # Always close a file once opened via open function.
>>> fp.closed
True 

# With Open syntax will handle the all the error handling internally and also closes files automatically.
>>> with open('testfl.txt','r+') as fp1:  
fp1.read()


'My first line\n\x00My Second Line\nMy Third Line\n'

>>> with open('testfl.txt','r+') as fp1:  
print fp1.read()


My first line
My Second Line

My Third Line

Tuesday, July 14, 2015

Special Methods in Python Explained.

We will try to understand these special methods via List Data Structure in Python. We can display the all the methods in List class by using dir(object) function. All the functions starting and ending with double underscore(__) forms a special methods in python.

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> lst1 = [1,2,3,4,5]
>>> lst2 = [6,7,8,9,10]
>>> lst1.__add__(lst2)  #Calling a basic addition between 2 lists it will be same as  lst1 + lst2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst1
[1, 2, 3, 4, 5]
>>> lst2
[6, 7, 8, 9, 10]
>>> lst1+lst2  # same as above operation
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst3 = lst1 + lst2
>>> lst3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>

If we perform a basic operations like +,-,*, the corresponding special methods will be called if that particular datatype supports that operation.

>>> lst1.__class__
<type 'list'>
>>> lst1.__contains__(1)
True
>>> 1 in lst1 # In operator internally calls above __contains__ spec method
True

>>> lst1.__delitem__(1)
>>> lst1
[1, 3, 4, 5]
>>> del lst1[0]  # calling shorthand del will internally calls __delitem__ as shown above.
>>> lst1
[3, 4, 5]

Operations attached to some of the special methods given here for reference.

'__delslice__',   <==> del lst1[i:j]
 '__doc__',          ==> documentation string
 '__eq__',           <==>    ==
 '__format__',    <==>  .format()
 '__ge__',           <==>    >=
 '__getitem__',   <==> lst1[i]
'__getslice__',    <==> lst1[i:j]
 '__gt__',            <==>    >

You can have operations shown below also.
 '__hash__',
'__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
 '__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__setslice__',
'__sizeof__',
'__str_

For More Information https://docs.python.org/2/reference/datamodel.html#special-method-names




Wednesday, July 8, 2015

Links to Python Resources in WEB:

Books:

1) ThinkPython PDF

WEB:


More Resources will be updated soon.

Program to sort the list as shown in output.
list1=['gt','abc','eabc','exxx','def','edef','ebcde']
output should be:
           ['eabc','ebcde','edef','exxx','abc','def','gt']   ....i.e items starting with 'e' and then remaining items sorted.


Solution:

def custom_sort(words):
  # Put each word into the x_list or the other_list.
  e_list = []
  other_list = []
  for word in words:

    # below if condition can be changed as "if word[0] == 'e':", Output will be same.
    if word.startswith('e'):
      e_list.append(word)
    else:
      other_list.append(word)
  return sorted(e_list) + sorted(other_list)

if  __name__ == '__main__':

   list1 = ['gt','abc','eabc','exxx','def','edef','ebcde']

   # Calling function defined
   list2 = custom_sort(list1)
   print list2
List & Tuples

List are mutable sequences, means we can change elements once declared. List creation syntax is given here.

>>> li = [1,2,3]
>>>li[2] = 5     #  possible in Lists

Tuples are immutable sequences, means tuples forms a constant list, once created we are unable to change the tuple elements.

>>> tp = (1,2,3)
>>> tp[2]
>>> 3     # it prints the 3rd element in tuple
>>> tp[2] = 5 # if you try to change the element of tuple will throw you a an error 
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    tp[2] = 5
TypeError: 'tuple' object does not support item assignment
>>>

Tuesday, June 16, 2015

Python Byte code -Pyc, Pyo

Python Byte code is a way of speed-up of the start-up time for short programs that use a lot of standard modules.

It will done automatically we need not do anything to generate pyc files.

pyc is compiled version of associated py file, if py file time stamp is not changed  then interpreter uses pyc file to link the program. If original py file changes then it will agian recreate pyc file in the same folder.

pyo files can be created using the python -o syntax.

The module compileall can create ".pyc" files (or ".pyo" files when -O is used) for all modules in a directory.