Python Classroom Series – 07/Dec/2019

Strings in Python.

  • creating string objects in python.
x = 'DevOps'
y = "DevOps"
z = """Multi line strings
can span across
multiple lines"""
  • Split string into list
x = 'some-value'
x.split('-')

Strings and file handling in Python

  • As discussed over in the class, please find the example below
import os
import stat
def getpath():
    return os.getenv('PATH')

def print_file_info(filename):
    file_stat = os.stat(filename)
    message = "filename: {}, file size: {}, lastmodified: {}".format(filename, file_stat[stat.ST_SIZE], file_stat[stat.ST_MTIME])
    print(message)

def show_all_folders_of_path():
    path = getpath()
    folders = path.split(';')
    for folder in folders:
        print(folder)

def find_existing_notexisting(folders):
    existing = []
    not_existing = []
    for folder in folders:
        if os.path.isdir(folder) and os.path.exists(folder):
            existing.append(folder)
        else:
            not_existing.append(folder)
    return {'existing': existing, 'not-existing': not_existing}


if __name__ == '__main__':
    folders = getpath().split(';')
    folder_dict=find_existing_notexisting(folders)
    print('existing folders are')
    for existing_folder in folder_dict['existing']:
        print(existing_folder)
    print('non existing folders are')
    for non_existing_folder in folder_dict['not-existing']:
        print(non_existing_folder)
    current_folder = folder_dict['existing'][1]
    print('tuple of ')
    for (root,dirs,files) in os.walk(current_folder):
        print(root)
        print(dirs)
        for file_found in files:
            try:
                print_file_info(os.path.join(current_folder,file_found))
            except Exception:
                print("error occurred for "+os.path.join(current_folder,file_found))
            
    

Specific Imports in Python

  • Create a file called utilities.py
class FileInfo(object):

    def __init__(self, filename):
        self.filename = filename

    def get_filename(self):
        return self.filename
    
    def set_filename(self, filename):
        self.filename = filename

SIZE = 10

SHAPE = 'RECTANGLE'


  • Create a new file called testimport1.py which imports only class FileInfo
from utilities import FileInfo

myfileinfo = FileInfo('temp.txt')
  • Create a new file called testimport2.py which imports SIZE and SHAPE
from utilities import SHAPE, SIZE

print(SIZE)
print(SHAPE)

  • create a new file called testimport3.py which imports every thing
import utilities

myfileinfo = utilities.FileInfo('temp.txt')
print(utilities.SHAPE)
print(utilities.SIZE)

Static Methods and Instance Methods

  • Create a simple class demonstrating instance and static method.
  • Create a class called as rectangle.py
class Rectangle(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2*(self.x + self.y)

    @staticmethod
    def Is_Rectangle(x, y):
        return x!=y

  • Use rectangle in other python file (testrectangle.py)
from rectangle import Rectangle

myrect = Rectangle(4,5)
myrect.perimeter()

print("Area of recatngle with x ={}, y = {} is {}".format(myrect.x, myrect.y, myrect.area()))
print("Perimeter of recatngle with x ={}, y = {} is {}".format(myrect.x, myrect.y, myrect.perimeter()))

print("If x = {} and y = {} then will it become Rectangle?  ==> {}".format(5,7,Rectangle.Is_Rectangle(5,7)))

print("If x = {} and y = {} then will it become Rectangle?  ==> {}".format(5,5,Rectangle.Is_Rectangle(5,5)))

Next Series Topics

  • Python Packaging – PIP
    • Boto3
    • Azure SDK for Python
  • Calling processes using python
  • Executing python programs on linux.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner