Archive for the ‘Scripts’ Category

Following script will loop through all Partner Center customers, will export them in batches of 100 and every “chunk” will be exported to separate CSV file.

 

$custIDs = Get-PartnerCustomer
$chunks = [System.Collections.ArrayList]::new()
for ($i = 0; $i -lt $custIDs.Count; $i += 100) {
    if (($custIDs.Count - $i) -gt 99  ) {
        $chunks.add($custIDs[$i..($i + 99)])
    }
    else {
        $chunks.add($custIDs[$i..($custIDs.Count - 1)])
    }
}
$today = [datetime]::Today.ToString("yyyy-MM-dd")
$count = 1
foreach ($chunk in $chunks) {
    $path = "c:\Reports\$today Chunk $count of $($chunks.Count).csv"
    $chunk | Export-Csv $path -Append
    $count++
}

This script will check if user password expires in 1,3 or 7 days and if yes, it will send email to user

 

First, encrypt password and store it in file

$password = "somepass"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPwd | ConvertFrom-SecureString
Set-Content "C:\temp\ExportedPassword.txt" $secureStringText

 

$mailuser = "userc@example.com"

$pwdmail = Get-Content "C:\temp\ExportedPassword.txt"
$securemailPwd = $pwdmail | ConvertTo-SecureString

$EmailCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $mailuser, $securemailPwd

$from = "user@xample.com"

# OU to search 

$path = "CN=Users,DC=example,DC=com"

$users = Get-ADUser -SearchBase $path -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0} `
-Properties "Name", "EmailAddress", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name", "EmailAddress", `
@{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring() }}

# Days remaining until password expiration
$WarningDays = 1,3,7

# Get current day
$today = (Get-Date).ToLongDateString()
try {
foreach ($user in $users)
{
 foreach ($WarnDay in $WarningDays){
 if ($user.PasswordExpiry -eq (get-date).adddays($WarnDay).ToLongDateString()) 
 {
  # Calculate days beteween today and date when password will expire
  $ts = New-TimeSpan -Start $today -End $user.PasswordExpiry
  $days = $ts.Days
  $subject = "Password expiration notification - " + $user.Name
  $body = "Dear " + $user.name + ",`nYour Password will expire in " + $days + " days"
  Send-MailMessage -to $user.EmailAddress -from $from -Subject $subject -Body $body -BodyAsHtml -SmtpServer smtp.office365.com -UseSsl -Credential $EmailCreds -Port 587

 }}}}
catch {
$Error[0].Exception.Message
}
exit $LASTEXITCODE
    from itertools import islice 

    def getListOfFiles(dirName):
    
    # create a list of file and sub directories 
    # names in the given directory 

    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)
                
    return allFiles  



dirName = "C:\SIEMLogs\Email"
 
listOfFiles = getListOfFiles(dirName)


# sort filenames by creation date (ascending)

sorted_files = sorted(listOfFiles, key=os.path.getmtime)

# select top 5 elements from sorted list

top_files = islice(sorted_files,5)
 

# Print top 5 files
for elem in top_files:
    print(elem)

# Number of files in sub directories

cpt = sum([len(files) for r, d, files in os.walk("C:\SIEMLogs\Email")])

print cpt
 

Listing files in directory (without sub directories),sorting by creation date (ascending) and count of total files:

path = "C:\SIEMLogs\Email"
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

for a in time_sorted_list:
    print a


# Number of files in Directory only

path, dirs, files = next(os.walk("C:\SIEMLogs\Email"))
file_count = len(files)

print file_count

This function will print registry value for specific key, in this case HPATH value

import _winreg

def getPath():
    # Open the key and return the handle object.
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                          "COMODO")
    
    # Read the value.                      
    result = _winreg.QueryValueEx(hKey, "MachineId")
    # Close the handle object.
    result = result[0]
    return result
    _winreg.CloseKey(hKey)

Another solution:

def regkey_value(path, name="", start_key = None):
    if isinstance(path, str):
        path = path.split("\\")
    if start_key is None:
        start_key = getattr(_winreg, path[0])
        return regkey_value(path[1:], name, start_key)
    else:
        subkey = path.pop(0)
    with _winreg.OpenKey(start_key, subkey) as handle:
        assert handle
        if path:
            return regkey_value(path, name, handle)
        else:
            desc, i = None, 0
            while not desc or desc[0] != name:
                desc = _winreg.EnumValue(handle, i)
                i += 1
            return desc[1]


posread = regkey_value(r"HKEY_LOCAL_MACHINE\COMODO", "MachineId")

3rd way:

import _winreg

reg_connection = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

key_value = _winreg.OpenKey(reg_connection, r"COMODO")

print _winreg.QueryValueEx(key_value, "MachineId")[0]

Reading registry keys from x64 versions of Windows using x86 Python installation:

import _winreg

def get_path(name):
    try:
        registry_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\\COMODO', 0, (_winreg.KEY_WOW64_64KEY + _winreg.KEY_READ))
        value = _winreg.QueryValueEx(registry_key, "MachineId")[0]     
        return value
    except WindowsError:
        return None

This class will accept 2 input parametrers:

one of type string and second of type integer, and we need to make sure second parameter needs to be integer

# function which tests for type:

def ensure_type(value, types):
    if isinstance(value, types):
        return value
    else:
        raise TypeError('Value {value} is {value_type}, but should be {types}!'.format(
            value=value, value_type=type(value), types=types))


class Account():
    def __init__(self, name, amount):
        self.name = name
        self.amount = amount

    def __str__(self):
        return "Account owner:" + self.name + '\nAmmount$: ' + str(self.amount)    
        
    def add(self, num):
        self.amount = self.amount + num
        return self.amount
    @property
    def name(self):
        return self.__dict__['name']

    @name.setter
    def name(self, value):
        self.__dict__['name'] = ensure_type(value, str)

    @property
    def amount(self):
        return self.__dict__['amount']

    @amount.setter
    def amount(self, value):
        self.__dict__['amount'] = ensure_type(value, int)

   


acc = Account('jose', 100)
 
print(acc)

print(acc.add(10))

Related posts:

 

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

Object Oriented Programming (OOP) allows programmers to create their own objects that have methods and attributes. For much larger scripts of python code,functions by themselved aren’t enough for organization and repeatability.

Commonly repeated tasks and objects can be defined with OOP to create code that is more usable.

Name of the class uses Camel case convention

CamelCase is a naming convention in which the first letter of each word in a name is capitalized. (StarCraft,FireHouse)

self” is the instance object automatically passed to the class instance’s method when called, to identify the instance that called it. “self” is used to access other attributes or methods of the object from inside the method. (methods are basically just functions that belong to a class)

Class syntax:

class NameOfClass():


    def__init__(self,param1,param2):
	   
	   self.param1 = param1
       self.param2 = param2	   

    
     # self is used to connect method to the class
     
    def some_method(self):
    
        # perform some action
        
        print(self.param1)

__init__ is special method (function) which creates instance of class object

param1 param2 input parameters to class

self.param1 self.param2 atributes of the class


Dog class accepts breed parameter and assigns it to breed attribute

class Dog():

    def __init__(self,breed):
    
        # assign breed atrubute  to self.breed
         
        self.breed = breed   


# create instance of class Dog

mydog = Dog("dalmatian")

# breed is attribute of class instance mydog

mydog.breed

'dalmatian'

Class object attributes

is attribute that belongs to any instance of class hence it’s globally visible.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed):

        self.breed = breed
        self.name = name

Create instance of Dog class

mydog = Dog("dalmatian")

Get class atributes

mydog.breed ‘dalmatian’

mydog.species ‘mammal’

Methods

are functions which takes class input parameters through self keyword

We added another class parameter – name

and added method bark() which returns name of the dog.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name):

        self.breed = breed
        self.name = name
       
    # method
    
    def bark(self):
        print(f'{self.name} barks')


mydog = Dog("dalmatian", "Pluton")

mydog.breed
'dalmatian'

mydog.species
'mammal'

# call method

mydog.bark()
Pluton barks

Methods can take arguments not specified in class inputs

In bark method we added number input, note that in print function it specified without self because this paramter is

“outside” of class, ie, it’s not specified during class definition.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name):

        self.breed = breed
        self.name = name
         
    def bark(self, number):
        print(f'{self.name} barks and number is {number}')


mydog = Dog("dalmatian", "Pluton")
mydog.breed

'dalmatian'

mydog.species
'mammal'


# supply number argument

mydog.bark(1)

Pluton barks and number is 1

Priniting class objects

If we want to print input parameters, we need to use

__str__ – convert objects to string


__len__ – convert objects to integers

Dog class now has 3 input paraneters:

strings (name and breed)

integers (number)

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name, num):

        self.breed = breed
        self.name = name
        self.num = num
    
    # return string atribute
    
    def __str__(self):

        return 'Name: ' + self.name + 'Breed: ' + self.breed    
    
    # return integer attribute
    
    def __len__(self):
        return self.num


    def bark(self, number):
        print(f'{self.name} barks and number is {number}')   

my_dog = Dog('husky','pluton', 1) 

len(my_dog)
1

str(my_dog)
'Name: pluton Breed: husky'

Inheritence

is creating new class from existing one. Derived class have all properties of base class (attributes and methods)

Base class:

class Animal():
    def __init__(self):
        print("Animal created")

    def who_am_i(self):
        print("I am an animal")

    def eat(self):
        print("I am eating")
        
        
        

my_animal = Animal()

Animal created

my_animal.eat()

I am eating

my_animal.who_am_i()

I am an animal

Creating Dog class from Animal class.

Dog class “inherits” all methods from Animal class.

class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print ("Dog created")



my_dog = Dog()

Animal created
Dog created

my_dog.eat()

I am eating

my_dog.who_am_i()
I am an animal

Methods from base class can be overriden in “child” (derived) class. It’s called Polymorphism.

Polymorphism

allows us to define methods in the child class with the same name as defined in their parent class.

Overriding eat() method.

In Dog class create same method as in base class and change it’s ouptut.

class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print ("Dog created")

    def eat(self):
        print("I'm a dog eating")


my_dog.eat()

I'm a dog eating

Abstract class

cannot be instantiated (objects cannot be created from it)

To create abstract class we need to import following namespace:

from abc import ABC,abstractmethod

ABC stands for abstract class and we need to add @abstractmethod above each method we do not want to instantiate.

from abc import ABC,abstractmethod
 class Animal(ABC):
     
  @abstractmethod
  def __init__(self, name):
      self.name = name
      print(f'Animal Created {self.name}')

f we now try to create instance from Animal class we’ll face expected error

TypeError: Can't instantiate abstract class Animal with abstract methods __init__

Let’s add another method to Animal class and derive Dog class from Animal.

from abc import ABC,abstractmethod
class Animal(ABC):
     
  @abstractmethod
  def __init__(self, name):
      self.name = name
      print(f'Animal Created {self.name}')
  # @abstractmethod 
  def eat(self):
    print(f'{self.name} eating')
 
 
class Dog(Animal):
  def __init__(self, name):
    self.name = name      
    # Animal.__init__(self)
    print(f'Animal Created {self.name}')    
 
# output
 
my_dog = Dog('tom')
'Animal Created tom'
my_dog.eat()
'tom eating'

Calling module from same folder

In Documents folder we have 2 files:

mymodule.py with simple function in it:

def my_func():
  print("My function")

myprogram.py from which we’ll call function in mymodule.py

To call function from another file we’ll use import keyword followed by file name, then we’ll simple call function from moymodule.py file (my_func)

from mymodule import my_func

my_func()

My Function

Calling modules from subfolders

Documents
        |
        |
        |
        MainPackage 
                   |
                   |                                      
                   |                                       
                   |                                       
                   __init__.py   some_main_script.py     SubPackage                                    
                                                                  |
                                                                  |
                                                                  |
                                                                  
                                                __init__.py   mysubscript.py                                                                 

Both __init__.py files are empty.The primary use of __init__.py is to initialize Python packages

Documents/MainPackage/some_main_script.py:

def report_main():
    print("Hey I'm in some_main_script in main package")

Documents/MainPackage/SubPackage/mysubscript.py:

def sub_report():
    print("Hey i'm function inside my subscript")

From Documents/myprogram.py parent folder we’ll call functions in Documents/MainPackage/some_main_script.py and Documents/MainPackage/SubPackage/mysubscript.py files

Documents/myprogram.py:

from keywords is followed by folder name and import is followed by file name located in that folder.

MainPackage/SubPackage corresponds to MainPackage.SubPackage, dot characters is used to express subfolders.

from MainPackage import some_main_script

from MainPackage.SubPackage import mysubscript

some_main_scrip.report_main()

Hey I'm in some_main_script in main package

mysubscript.sub_report()

Hey i'm function inside my subscript

Related articles:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

LEGB is acronim of:

L:Local – Names assigned in any way within a function (def or lambda) and not declared global in that function.

E:Enclosing function locals – Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.

G:Global (module) – Names assigned at the top-level of a module file. or declared global in a def within the file.

B:Built-in (Python) – Names preassigned in the built-in names module:open,range,SyntaxError.

Local scope refers to variables defined in current function.Always, a function will first look up for a variable name in its local scope. Only if it does not find it there, the outer scopes are checked.

name = 'This is a global string'

   def myfunc():
      name = "Hello World"
      print(name)

myfunc()
Hello World

In above example we have 2 variables with same name and when function is executed, it’s looking into it’s own namespace (name=’Hello World’), in case there is no variable name inside “enclosing function” – myfunc(), then global name string would be applied, below example illustrates this:

name = 'This is a global string'

   def myfunc():
       print(name)

myfunc()
This is a global string

Let’s look at next example:

x =  50

def func(x):
     print(f'X is {x}')
     
     # Local reassignment
     x = 200
     print(f'I just changed X to {x} locally')

func(x)

X is 50
I just changed X to 200 locally

print(x)
50

So we get 50 for X although we changed it’s value to 200, it’s because assignment happens only inside local namespace (inside this function), it’not going to affect any variable outside function itself (higher scope).


If we need to “override” global variable we can do it in following way:

we declared global x variable global x, so function will tell python: go to namespace, jump to the global level and get x value, then assign new value to that global variable locallyx = 'new value' and apply changes on global level.

x =  50

def func():
     global x

     print(f'X is {x}')
     
     # Local reassignment on a global variable 
     x = 'new value'
     print(f'I just locally changed global X to {x}')

func()
X is 50
I just locally changed global X to new value
print(x)
new value

Above approach is potentially dangerous because we change global variable value so safer solution would be to assign output of function to global variable, without changing it:

x =  50

def func(x):
     print(f'X is {x}')
     
     # Local reassignment 
     x = 'new value'
     print(f'I just locally changed global X to {x}')
     return x


x = func(x)
X is 50
I just locally changed global X to new value
print(x)
new value

Related posts:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

Booleans are operators used to express True or False statements, used for performing comparations.Needs to be capitalized True is not equal to true and False is not equal to false.None used to define null value or no value at all.

If elif and else statements

if some_condition: 

   # execute some code 

elif some_other_condition: 

   # execute_some_other_code 

else: 

   # do something else


############################################################## 

# print response based on input code

code = 'CA' 

if code == 'CA': 

  print("CA is California") 

elif code == 'CO': 

  print("CO is Colorado") 

elif code == 'CT': 

  print("CT is Connecticut") 

else: 

  print("Invalid. Please enter a valid state code that starts with letter C") 

For Loops

We can iterate over every element in many objects in Ptyhon. Executing block of code for every iteration is possible using for loops.Bellow code will print list value (1,2,3).Item_name is arbitrary variable, it represents values in my_iterable list.For every value (item_name) in my_iterable list, print that value.

 

my_iterable = [1,2,3] 

for item_name in my_iterable: 

  print(item_name) 
1
2
3

Getting dictionary key pairs

d = {'k1':1,'k2':2,'k3':3} 

for item in d.items(): 

    print(item) 

 ('k1', 1) 

('k2', 2) 

('k3', 3) 

  

  

# getting values 
for item in d.values(): 

    print(item) 

1 
2 
3 

  

# another way  

  
for key,value in d.items(): 
    print(value) 

while loops executes a block of code while some conditions remains True.

while some_boolean_condition: 

   #do something 

While will execute until x is less than 5, otherwise, it will print “X is not less than 5”

x = 0 

while x < 5:
    print(f'The current value of x is {x}') 
    x = x + 1 
else: 
    print("X is not less than 5")    

The current value of x is 0 
The current value of x is 1 
The current value of x is 2 
The current value of x is 3 
The current value of x is 4 
X is not less than 5 

break,continue and pass statements.

break: Breaks out of the current loops

continue: goes to the top of cuttent loops

pass: does noting at all (prevents errors)

Bellow is example for pass

x = [1,2,3] 

    for item in x: 
    # nothing 
    print('end')  
  IndentationError: expected an indented block 

# adding pass will prevent syntax error and won't do anything else

x = [1,2,3] 
  for item in x: 
     # nothing 
  pass 
  print('end') 

end 

continue

In below examplw,when for loop finds ‘e’ character, it will simply go back at the begging of the loop, it won’t process ‘e’ character.

string = 'Hello' 
for letter in string: 
   if letter == 'e': 
      continue 
   print(letter)    
H 
l 
l 
o    

Break will simple stop executing code when it faces ‘e’ character.

string = 'Hello' 
for letter in string: 
   if letter == 'e': 
       break 
   print(letter)  
H    

Range function prints number in specified range except last number (10 in this case)

a = list(range(1,10))
print (a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

range function includes another parameter:step.

The step is a difference between each number in the result.

for num in range(3,11,2):
    print(num)
3
5
7
9

List comprehension is an other way how to iterate through list instead of for loop

# for loop
my_string = 'hello'
my_list = []
for letter in my_string:
    if 'l' in letter:
        print(True)
    else:
        print(False)

# output
False
False
True
True
False

# List comprehension

['True' if 'l' in letter else 'False' for letter in my_string] 

Enumerate function creates index of items in for loop iteration for every location in variable

word = "abcde" 

for item in enumerate(word): 
   print(item) 
(0, 'a') 

(1, 'b') 

(2, 'c') 

(3, 'd') 

(4, 'e') 

zip function zips 2 or more lists returns list of tuples
(pairs up one element in one list with element in other list at same index )

mylist1 = [1,2,3] 
mylist2 = ['a','b','c']

for item in zip(mylist1,mylist2):
    print(item)

(1, 'a')
(2, 'b')
(3, 'c'

If 2 lists are not even, zip returns pair for shortest list

mylist1 = [1,2,3,4,5,6]
mylist2 = ['a','b','c']

for item in zip(mylist1,mylist2):
   print(item)

(1, 'a')
(2, 'b')
(3, 'c')

We can convert tuples to list using zip

list(zip(mylist1,mylist2))
[(1, 'a'), (2, 'b'), (3, 'c')]

in operator – checks if statement is true or false

# check if x is in list 

'x' in [1,2,3]
False

'x' in ['x','y','z']
True

# check if a is in string 

'a' in 'a word'
True

# check if mykey is in dictionary 

'mykey' in {'mykey':345}
True


d = {'mykey':345}
345 in d.values ()
True
345 in d.keys()
False
345 in d.items()
False

prompt user for input using string

a = input('Enter something')

# input as number

number = input("Enter a number")

int(number)

Functions allows creating block of code that can be executed multiple times without need to rewrite block of code.
Return keyword sends back function results, so we can assign this output to variable.

def function_name():
   
   return ("Hello")
   

Functions output can be assigned to variables.

output = function_name()

print(output)

Hello

Add parameter to function.

def printme( str ):
    "This prints a passed string into this function"
    return str

printme("I'm first call to user defined function!")

*args and **kwargs

def myfunc(a,b):
    return sum((a,b)) 


myfunc(8,2,1)

TypeError: myfunc() takes 2 positional arguments but 3 were given

If, in above function, we supplied more parametes than needed, then we get error.To enable function to take arbitrary number of paramters we can use *args, and specify as many parameters as we want.
Input parameters are treated as tuple (a,b,c….).

def myfunc(*args):
    return sum(args)

**kwargs creates argument of keypairs, it returns dictionary, and accepts named arguments.In next example,if user passes other argument than city, it won’t be returned but also won’t throw an error.

def myfunc(**kwargs):
    
    if 'city' in kwargs:
        return ('My favorite city is  {}'.format(kwargs['city']))
    else:
        return ("Didn't find any city")    

myfunc(city = 'Zemoon',river = 'Danube')

'My favorite city is  Zemoon'

Map function

passes every single element of list to function, so instead of running custom function multiple times for every string in list, map simple passes every string to our function in “one go”

In this example function will print “EVEN” for string whose lenght is even number, othervise, it will print first letter of non-evcen string.

def splicer(mystring):
    if len(mystring)%2 == 0:
        return 'EVEN'
    else:
        return mystring[0]

Now, we can use map to call splicer function and it’s parameter (names)

names = ['Andy','Eve','Sally']

for item in map(splicer,names):
    print(item)
EVEN
E
S

filter function returns an iterator were the items are filtered through a function to test if the item is accepted or not (True) This function accepts numbers, and if input parameter is less than 18, it returns False, othervise, returns True

def myFunc(x):
  if x < 18:
    return False
  else:
    return True

Filter function, will iterate through all elemets in ages list and will return only values which are True.

ages = [5, 12, 17, 18, 24, 32]

adults = filter(myFunc, ages)

for x in adults:
  print(x)

18
24
32

Lambda is function that’s defined without name While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Here is equivalet of above myFunc function.

ages = [5, 12, 17, 18, 24, 32]

adults = list(map(lambda x: True if (x > 18) else False,ages))

print(adults)

[False, False, False, False, True, True]

To print only values x>18, again we’l use filter function.

adults = list(filter(lambda x: True if (x > 18) else False,ages))

print(adults)

[24, 32]

return first character of string

names = ['Andy', 'Eve', 'Sally']
first_letter = list(map(lambda x:x[0], names))
print(first_letter)
['A', 'E', 'S']

Related posts:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

 

Get current directory path and list files in it:

import os

dirpath = os.getcwd()
files = [ f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath,f)) ] 
print('Files:{f} in {d}'.format(f = files ,d = dirpath)) 

# change directory to dirpath 
os.chdir(dirpath) 

File modes:

‘r’ – read only

‘w’ – write (will overwrite file or create new)

‘a’ – append (add new lines in file)

‘r+’ – reading and writing

‘w+’ – writing and reading (overwrites exiting files or creates a new one)

# Write to file 

file1 = open("myfile.txt","w")  
file1.write("This is Delhi\nThis is Paris\nThis is London\n") 
file1.close() 

  
# read file 

file1 = open("myfile.txt","r")  
file1.readlines() 
file1.close() 

In above examples we need to manually close files using close() method.

Using “with” directives files are automatically closed after writing/reading

# read file and automatically close file  

with open('myfile.txt') as my_file: 
    content = my_file.read() 

# write to file 
 
with open('myfile.txt', 'w') as my_file: 
  my_file.write("This is Delhi\nThis is Paris\nThis is London\n") 

# append new line to file 
with open('myfile.txt', 'a') as my_file: 
  my_file.write("This is Zemoon\n")