Tuesday, February 1, 2022

glob in python

 


import glob
glob.glob('./[0-9].*')
#['./1.gif', './2.txt']
glob.glob('*.gif')
#['1.gif', 'card.gif']
glob.glob('?.gif')
#['1.gif']
glob.glob('**/*.txt', recursive=True)
#['2.txt', 'sub/3.txt']
glob.glob('./**/', recursive=True)



# =============================================================================
#
# =============================================================================
import os

path=os.listdir("C:/Users")
print(path)

# =============================================================================
#

# =============================================================================

import glob
glob.glob('C:/')

Date and time in python using datetime modules

 



import datetime

year_number=2021
month_number=12
date_number=27
hours_number=15
minutes_number=50
seconds_number=30

datetime.datetime(year_number, month_number, date_number, hours_number, minutes_number, seconds_number)



# =============================================================================
#
# =============================================================================

import datetime

print (datetime.date.today())


# =============================================================================
#
# =============================================================================

from datetime import date

print (date.today())





# =============================================================================
#
# =============================================================================

from datetime import date

print (datetime.date.today().day)

print (datetime.date.today().month)

print (datetime.date.today().year)

#If you prefer to write in one sentence, write it as

print (datetime.date.today().day,datetime.date.today().month,datetime.date.today().year)




# =============================================================================
#
# =============================================================================

from datetime import date

now = date.today()

print (now.day)

print (now.month)

print (now.year)

#You can also display the previous 3 sentences in one sentence

print (now.day, now.month, now.year)

#This code is cleaner and compact. Try to write the code in shortest way possible without affecting readability.


# =============================================================================
#
# =============================================================================

from datetime import date

now = date.today()

print (now.weekday())



# =============================================================================
#
# =============================================================================

Today = datetime.now()

print (Today.strftime("%a, %B, %d, %y"))





# =============================================================================
#
# =============================================================================

import datetime

Today = datetime.now()

print ("Today’s date is" ,Today.strftime("%c"))



# =============================================================================
#
# =============================================================================

from datetime import date,time,datetime,timedelta

Time_gap = timedelta(hours = 23, minutes = 34)
#Time_gap is the timedelta object where we can do different calculations on it.

print ("Future time is ", str(datetime.now() + Time_gap))



config parser in python

 import configparser

config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)


# =============================================================================
#
# =============================================================================


config = configparser.ConfigParser()
config.sections()
#[]
config.read('example.ini')
#['example.ini']
config.sections()
#['bitbucket.org', 'topsecret.server.com']
'bitbucket.org' in config
#True
'bytebong.com' in config
#False
config['bitbucket.org']['User']
#'hg'
config['DEFAULT']['Compression']
#'yes'
topsecret = config['topsecret.server.com']
topsecret['ForwardX11']
#'no'
topsecret['Port']
#'50022'
for key in config['bitbucket.org']:
print(key)
#user
#compressionlevel
#serveraliveinterval
#compression
#forwardx11
config['bitbucket.org']['ForwardX11']
#'yes'

excel opening with python and coloring the cells

 

from win32com.client.gencache import EnsureDispatch



    Application                  = EnsureDispatch("Excel.Application")

    Application.DisplayAlerts    = False

    Application.Visible          = True

    Application.AskToUpdateLinks = False

    Application.EnableEvents     = False

    

    mapping_wb                   = Application.Workbooks.Open(os.path.join(os.getcwd(), "test.xlsx"))

    ws                           = mapping_wb.Worksheets("color_check")

    

    ws.Range(f"A{1}").Value = "This is testing"

    

    #time.sleep(10)

    #ws.RefreshAll()

    #mapping_wb.FillColor("red")

    

    #ws.Cells(1,4).Value = "Coin Toss Results"  #This is Row D

    #ws.Range(f"A{4}").Value = "coint toss Results"

    

    cell = ws.Cells(2,4)

    cell.Interior.Color = rgbToInt((255,0,0))

    

    

    for i in range(2,5):   # Assuming there is Cell(D2)=1, Cell(D3)=0, Cell(D4)=-1

        cell = ws.Cells(i,4)

        if cell.Value < 0:

            cell.Interior.Color = rgbToInt((255,0,0)) # red

        elif cell.Value == 0:

            cell.Interior.Color = rgbToInt((211,211,211)) # grey

        elif cell.Value > 0:

            cell.Interior.Color = rgbToInt((0,255,0)) # green

        else:

            print('Error.')

        

    ws.Columns.AutoFit()

    mapping_wb.Save()

    

    print("refresh done")

Wednesday, January 5, 2022

try except blocks checking

 try :

    print("try 1")

except:

    print("except1")


try :

    print("try 2")

except:

    print("except2")

    


try :

    print("try 3")

except:

    print("except3")


try :

    print("try 4")

except:

    print("except4")


output:

     try 1

try 2

try 3

try 4

Saturday, December 25, 2021

date time in python

 # ========================================================================

# date time using python

# ========================================================================


#uncomment to import library 

import pandas as pd 

import datetime as dt


#converting string into datetime 

df1 = pd.DataFrame(

     {

      "DateTime": pd.to_datetime(["2021-11-13 13:45:33",

                                  '2021-11-14 14:13:25',

                                  "2021-11-15 14:39:25", 

                                  "2021-11-16 15:16:43", 

                                  "2021-11-17 16:51:19"]),

     }

)


#split datetime into individual date and time df column

df1['Dates'] = pd.to_datetime(df1['DateTime']).dt.date

df1['Time'] = pd.to_datetime(df1['DateTime']).dt.time


#join date and time columns into a datetime column 

df1['DateTime_join'] = pd.DataFrame(

    pd.to_datetime(df1['Dates'].astype(str) + ' ' + df1['Time'].astype(str)), 

    columns=['Datetime_join']) 

print(df1)



# ========================================================================

# date time format change

# ========================================================================

import pandas as pd

dt = "02-11-2021"

dt1 = pd.to_datetime(dt)

dt1

#output# Timestamp('2021-02-11 00:00:00')

dt2 = pd.to_datetime(dt, format = "%d-%m-%Y")

dt2

#output# Timestamp('2021-11-02 00:00:00')



# ========================================================================

# date time format

# ========================================================================


import pandas as pd

dt = pd.to_datetime("02-11-2021")

dt3 = dt.strftime('%b/%d/%Y')

dt3

#output# 'Feb/11/2021'



Monday, December 13, 2021

Top 4 interview questions of python

 Write a program  on decorator?


def decor1(func):

    def wrapper():

        print("this is beauty function")

        func()

        

    return wrapper

    

  

def func1():

    print("this is the normal function")

    


func1 = decor1(func1)

func1()


#2. Write a code for fibonacci series upto 1000

a,b=0,1


while b<1000:

    print(b,end=',')

    a,b=b,a+b


output:

1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987


#3.Write a code for show the list indexes with list values?

list1=[1,2,3,4,5]    

for index,value in enumerate(list1):

    print("index-"+str(index)+" value-"+str(value))

output:

index-0 value-1

index-1 value-2

index-2 value-3

index-3 value-4

index-4 value-5



a = 99311278

list1=[]


def sort1(x):

    list1.append(b)

    list1.sort()

     

for i in range(1,9):

         b=a%10

         a =int(a/10)

         #print(a)

         #print(b)

         sort1(b)


print(list1)






    

Thursday, December 9, 2021

python interview questions of inventech solutions

 1.difference between list and tuple?

2.is string is mutable or not?

3.how to remove duplicates from the list

4.what is set in python?

5.what is the lambda function

6.numpy: how to fetch the 5 columns randomly from CSV files

7.How to Copy "A" table with 1 lakh column into empty table "B"

8.query for fetching highest salary employee details from employee table?



Answers:

 1.difference between list and tuple?

ans:



2.is string is mutable or not?

ans: string are immutable. we can't add anything at runtime

3.what is the lambda function

ans:What is Lambda Function in Python? Lambda Function, also referred to as 'Anonymous function' is same as a regular python function but can be defined without a name. While normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword.

4.how to remove duplicates from the list?


5.what is set in python?

6.numpy: how to fetch the 5 columns randomly from CSV files

7.How to Copy "A" table with 1 lakh column into empty table "B"

8.query for fetching highest salary employee details from employee table?

Wednesday, December 8, 2021

Polymorphism in python

 polymorphism means one function with multiple forms. one function can act like multiple functions.

Example:

#polymorphism


print(len("hello"))


print(len([10,20,30]))



output:

5

3



#your defined  polymorphism


def poly_test(a,b,c=0):

    print(a+b+c)

    

poly_test(10,20)

poly_test(10,20, c=30)


output :

30

60

python classes

 class anil_test2:

    a = 10

    

    def ani_test():

        print(" This class inside function")

        

        

        

print(anil_test2)


python functions test1

 


def anil():

    print("testing the values")

    

anil()


def anil_test():

    print("testing is working")

    

    

anil_test()

python class topic video