Tuesday, May 3, 2022

python with mysql topic 1(How to create db)

 using python we can create our on DB using python in mysql.

please follow the below lines of code

import pymysql

#create the database connections

con =  pymysql.connect(host ="localhost",user = "root",password='')

#create the cursor object

cursor =  con.cursor()

#execute the query

cursor.execute('CREATE DATABASE ANIL2')

#print the statement

print("database created successfully")



copy the above lines in Any python IDE, open mysql server. then run the above code you will see the Anil2 Database in Mysql

Thursday, March 17, 2022

file operations in python

 # -*- coding: utf-8 -*-

"""

Created on Wed Feb 23 06:55:56 2022


@author: durga

"""


# import os



# file1 = open("test123.txt")


# print(file1)


# file1 = open("img.jpg")


# print(file1)

# print(file1.read())


# file1 = open("employee_class.py")


# print(file1)

# print(file1.read())


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

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


# file2 = open("D:/python/Evening_batch/entry_test.py")

# print(file2)

# print(file2.read())


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

# file modes

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

# r = read default

# a = append mode

# w = write mode and opens also

# x = create  new



# file1 = open("test.txt",'r')

# print(file1)

# print(file1.read())



# file1 = open("test.txt",'a')

# print(file1)


file1 = open("test.txt",'w')

print(file1)


for i in range(100,200):

    file1 = open(f"test6{i}.txt",'x')

    print(file1)


#t= text default, text mode

#b= binary mode..(images)



# file1 = open("test.txt",'r')

# print(file1.read())




# file2 = open("D:/python/morning_class/test7.txt",'r')

# print(file2.read())


# file2 = open("D:/python/morning_class/test.txt",'r')

# print(file2.read(7))


# file2 = open("D:/python/morning_class/test.txt",'r')

# print(file2.read(10))


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

# readline()

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

# file2 = open("D:/python/morning_class/test.txt",'r')

# print(file2.readline())

# print(file2.readline())

# print(file2.readline())

# print(file2.readline())

# print(file2.readline())





# file2 = open("D:/python/morning_class/test.txt",'r')

# print(file2.readline(10))

# print(file2.readline(7))


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

# close the files

#variable.close()

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

file2 = open("D:/python/morning_class/test.txt",'r')

print(file2.readline(10))

# file2.close()

# print(file2.readline(10))



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

# write the extra lines

#variable.write()

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

file2 = open("D:/python/morning_class/test.txt",'a')

file2.write("extraline append to  nextline")


file2 = open("D:/python/morning_class/test.txt",'r')

print(file2.read())

file2.close()


#file2 = open("D:/python/morning_class/test.txt",'r')

print(file2.read())



file2 = open("D:/python/morning_class/test9.txt",'x')

file2.write("extraline append to  nextline")


# file2 = open("D:/python/morning_class/test9.txt",'r')

# print(file2.read())

# file2.close()



# a= dir(os)

# print(a)


#CRUD----create,read,update,delete

# os.remove("test7.txt")





abstract base class in python



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

# example 4

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

# Python program invoking a

# method using super()


import abc

from abc import ABC, abstractmethod


class A(ABC):

def fun1(self):

print("Abstract Base Class")


class K(A):

def fun2(self):

super().fun1()

print("subclass ")


# Driver code

r = K()

r.fun2()







# -*- coding: utf-8 -*-

"""

Created on Mon Mar  7 23:10:32 2022


@author: durga

"""


# Python program showing

# abstract base class work

# Python program showing

# abstract base class work


# from abc import ABC, abstractmethod


# class Animal(ABC):

# def move(self):

# pass


# class Human(Animal):

# def move(self):

# print("I can walk and run")


# class Snake(Animal):

# def move(self):

# print("I can crawl")


# class Dog(Animal):

# def move(self):

# print("I can bark")


# class Lion(Animal):

# def move(self):

# print("I can roar")

#

# # Driver code

# R = Human()

# R.move()


# K = Snake()

# K.move()


# R = Dog()

# R.move()


# K = Lion()

# K.move()






# from abc import ABC, abstractmethod


# class Polygon(ABC):


# @abstractmethod

# def noofsides(self):

# pass


# class Triangle(Polygon):


# # overriding abstract method

# def noofsides(self):

# print("I have 3 sides")


# class Pentagon(Polygon):


# # overriding abstract method

# def noofsides(self):

# print("I have 5 sides")


# class Hexagon(Polygon):


# # overriding abstract method

# def noofsides(self):

# print("I have 6 sides")


# class Quadrilateral(Polygon):


# # overriding abstract method

# def noofsides(self):

# print("I have 4 sides")


# # Driver code

# R = Triangle()

# R.noofsides()


# K = Quadrilateral()

# K.noofsides()


# R = Pentagon()

# R.noofsides()


# K = Hexagon()

# K.noofsides()






# Python program showing

# implementation of abstract

# class through subclassing


# import abc


# class parent:

# def geeks(self):

# pass


# class child(parent):

# def geeks(self):

# print("child class")


# # Driver code

# print( issubclass(child, parent))

# print( isinstance(child(), parent))







# Python program showing

# abstract properties


import abc

from abc import ABC, abstractmethod


class parent(ABC):

@abc.abstractproperty

def geeks(self):

return "parent class"

class child(parent):

@property

def geeks(self):

return "child class"


try:

r =parent()

print( r.geeks)

except Exception as err:

print (err)


r = child()

print (r.geeks)

c# variables


using System;

namespace HelloWorld

{


    public class lecture

    {

        public int age;//This is the variable type of integer


        //entry point of the our program

        public static void Main(string[] args)

        {

            int age = 15;

            string name = "srilatha";

            float p = 15.4f;

            bool is_working = true;

            char c = 'a';



            Console.WriteLine(age);

            Console.WriteLine(name);

            Console.WriteLine(p);

            Console.WriteLine(c);

            Console.WriteLine(is_working);



            Console.Read();

        }

    }

}




output:

15

srilatha

15.4

a

True

Monday, February 7, 2022

how to open excel , an excel instances in python

     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")

    


file_path           =   os.path.join(input_folder,test_file_name)


            test_workbook                  =   Application.Workbooks.Open(file_path)


            test_sheet                  =   test_workbook.Worksheets("test_sheet")


            Application.Worksheets("test_sheet").Activate()


Wednesday, February 2, 2022

how to use pandas iloc


data.iloc[0] # first row of data frame (Aleshia Tomkiewicz) - Note a Series data type output.
data.iloc[1] # second row of data frame (Evan Zigomalas)
data.iloc[-1] # last row of data frame (Mi Richan)
# Columns:
data.iloc[:,0] # first column of data frame (first_name)
data.iloc[:,1] # second column of data frame (last_name)
data.iloc[:,-1] # last column of data frame (id) Multiple columns and rows can be selected together using the .iloc indexer.

data.iloc[0:5] # first five rows of dataframe
data.iloc[:, 0:2] # first two columns of data frame with all rows
data.iloc[[0,3,6,24], [0,5,6]] # 1st, 4th, 7th, 25th row + 1st 6th 7th columns.
data.iloc[0:5, 5:8] # first 5 rows and 5th, 6th, 7th columns of data frame (county -> phone1).

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")

python class topic video