Skip to main content

Posts

Showing posts with the label Python Programming

Find and replace multiple text in a file using Python

Here is a code which shows how to find and replace multiple text in a file using Python: search_text_1 = "36419" search_text_2 = "250847" search_text_3 = "2764437" search_text_4 = "OOGGT" i=1 for j in range(2000):     with open('C:\\Users\\Original\\'               'source_filename.txt', 'r') as file:         data = file.read()         GS = int(search_text_1) + i         data1 = data.replace(search_text_1, str(GS))     with open('C:\\Users\\Original\\Champ\\'               'E_EI4.20213.024.35.X1.243_' + str(i) + '.txt', 'w') as file:         file.write(data1)     with open('C:\\Users\\Original\\Champ\\'               'E_EI4.20213.024.35.X1.243_' + str(i) + '.txt', 'r') as file:         data = file.read()         N9 = int(search_text_2) ...

Create empty files with same name and different extension in python

 Below is the program to Create empty files with same names and different extensions present in a specific directory in python. Here is the code: import glob import os path = 'C:\\Users\\Test\\Documents\\2025\\August\\6 Aug\\Email\\' add_extension = ".ok" i=1 for i, filename in enumerate(glob.glob(path + '*.xml')):     new_filename = filename + add_extension     try:         with open(new_filename, 'w') as f:             pass  # No content is written, so the file remains empty         print(f"Empty file '{new_filename}' created successfully.")     except IOError as e:         print(f"Error creating file: {e}")

Python - Connect to MariaDB

 Below is the Python program which will show you how to connect to MariaDB. Here is the code:  # Module Imports import mariadb import sys # Connect to MariaDB Platform try:     conn = mariadb.connect(         user="user",         password="password",         host="host",         port=port,         database="database"     ) except mariadb.Error as e:     print(f"Error connecting to MariaDB Platform: {e}")     sys.exit(1) # Get Cursor cur = conn.cursor() try:     cur.execute("show databases;")     cur.execute("use test_db;")     cur.execute("show tables;")     for table in cur:         print(table) except mariadb.Error as e:     print(f"Error: {e}") # Close Connection conn.close()

Python - get file attributes or file related information

 Below is the Python program which will get file attributes or file related information. Here is the code:  import os import sys sys.path.extend(r'mention your file path here') print('Get current working directory : ', os.getcwd()) print('File name :    ', os.path.basename(__file__)) print('Directory Name:     ', os.path.dirname(__file__)) print('Absolute path of file:     ', os.path.abspath(__file__)) print('Absolute directory name: ', os.path.dirname(os.path.abspath(__file__))) # Specify the directory you want to list directory_path = os.getcwd() # List all files and folders in the directory file_list = os.listdir(directory_path) # Get full paths full_paths = [os.path.join(directory_path, file) for file in file_list] print(full_paths)

Python - SFTP connection, upload file and delete a file from SFTP server

 Below is the python program which will connect to SFTP server, upload a file to SFTP server and delete a specific file from SFTP server. Here is the code: import paramiko from paramiko.ssh_exception import SSHException import os import time hostname = 'hostname here' username = 'username here' password = 'password here' port = PORT_NO SSH_Client = paramiko.SSHClient() SSH_Client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) SSH_Client.connect(hostname=hostname,                    port=port,                    username=username,                    password=password,                    look_for_keys=False) sftp_client = SSH_Client.open_sftp() print("Connection successfully established ... ") remoteFilePath = "/home" # Output: lists of files ['my-directory', 'my-file'] print(f"li...

Python - Change filename for all files present in a specific folder

 Following is the Python program which will Change filename for all files present in a specific folder. Following is the code. import glob import os path = 'path to folder' i=1 for i, filename in enumerate(glob.glob(path + '*.xlsx')):     os.rename(filename, os.path.join(path, 'QA_Scenario_1__' + str(i+1) + '.xlsx')) j=i for j, filename in enumerate(glob.glob(path + '*.xls')):     os.rename(filename, os.path.join(path, 'Testing_Scenario_1__' + str(j+1) + '.xls'))

Some GUI examples in Python using customtkinter

 Some GUI examples in Python using customtkinter import customtkinter import os from PIL import Image class ScrollableCheckBoxFrame(customtkinter.CTkScrollableFrame):     def __init__(self, master, item_list, command=None, **kwargs):         super().__init__(master, **kwargs)         self.command = command         self.checkbox_list = []         for i, item in enumerate(item_list):             self.add_item(item)     def add_item(self, item):         checkbox = customtkinter.CTkCheckBox(self, text=item)         if self.command is not None:             checkbox.configure(command=self.command)         checkbox.grid(row=len(self.checkbox_list), column=0, pady=(0, 10))         self.checkbox_list.append(checkbox)     def remove_item(self, it...

File Compare Tool in Python and tkinter

 Below is the desktop application developed in Python to compare 2 files and find out the differences. Here is the code: import tkinter as tk from tkinter import filedialog from tkinter import ttk import time import threading class TextComparerApp:     def __init__(self, root):         self.root = root         self.root.title("Text Compare: by Vinayak")         self.root.geometry("800x730")  # Set default window size to 800x730 pixels         # Frame to hold upload buttons         self.upload_frame = tk.Frame(root)         self.upload_frame.pack(pady=10)         # First file upload button         self.upload_button1 = tk.Button(self.upload_frame, activebackground="#99e0aa", text="<--- Insert File 1 --->",                             ...

Add worklog in Jira using Python

 Below is the Python code to add the worklog in Jira. You need to install a request library for this. Here is the code: import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/rest/api/2/issue/ticket_number/worklog" auth = HTTPBasicAuth("username", "jira access token") headers = {     "Accept": "application/json",     "Content-Type": "application/json" } payload = json.dumps({     "comment": {         "content": [             {                 "content": [                     {                         "text": "This is for QA Testing",                         "type": "text"                     } ...

create a groups in Jira API using Python

 Below is the Python code to get create a groups in Jira. You need to install a request library for this. Here is the code: import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/rest/api/3/group" headers = {   "Accept": "application/json",   "Content-Type": "application/json" } payload = json.dumps( {   "name": "QA" } ) response = requests.request(    "POST",    url,    data=payload,    headers=headers,    auth=auth ) print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

Python code to get the groups in Jira

 Below is the Python code to get the groups in Jira. You need to install a request library for this. Here is the code: import requests url = "https://your jira address here/rest/api/2/user/groups?Name=jira name " \       "&accountId=account-id&username=username " payload={} headers = {    'User-Agent': 'Apidog/1.0.0 (https://apidog.com)' } response = requests.request("GET", url, headers=headers, data=payload) print(response.text) ============================================================= import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/rest/api/3/group" auth = HTTPBasicAuth("username", "jira access token") headers = {     "Accept": "application/json" } query = {     'groupId': 'groupId' } response = requests.request(     "GET",     url,     headers=headers,     params=query,     auth=auth ) print(js...

Get all the users from a group in Jira using Python

 Below is the Python code to get all the users from a group in Jira. You need to install a request library for this. Here is the code: import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/rest/api/3/group/member" auth = HTTPBasicAuth("username", "jira token mention here") headers = {   "Accept": "application/json" } query = {   'groupId': '6078c76f-bf47-4573-a150-b9f0285ac8aa' } response = requests.request(    "GET",    url,    headers=headers,    params=query,    auth=auth ) print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

Create worklog in Jira using Python

Below is the Python code to Create worklog in Jira. You need to install a request library for this. import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/worklog" auth = HTTPBasicAuth("username", "jira token mention here") headers = {   "Accept": "application/json" } response = requests.request(    "GET",    url,    headers=headers,    auth=auth ) print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

Capture Network Traffic in Python

  Below is the code to capture a network traffic in python import requests def check_web_traffic (url): try : response = requests.get(url) if response.status_code == 200 : print ( f"Web traffic for { url } is good." ) else : print ( f"Web traffic for { url } is not as expected. Status code: { response.status_code } " ) except requests.RequestException as e: print ( f"An error occurred: { e } " ) if __name__ == "__main__" : url = 'Put website url here' check_web_traffic(url)

Create Progress bar in Python

Following is the code to create a  Progress bar in Python. For that you need to install  tqdm package Here is the code: from tqdm import tqdm from time import sleep pbar = tqdm( total = 100 ) for i in range ( 10 ): sleep( 0.2 ) pbar.update( 10 ) pbar.close()

Generate Logs in Python

 Below is the code which will show how Logging is done in Python: import logging import time class Logger: def __init__ ( self , logger , file_level=logging.info): self .logger = logging.getLogger(logger) self .logger.setLevel(logging.INFO) """ self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.INFO) self.logger.setLevel(logging.WARNING) self.logger.setLevel(logging.ERROR) self.logger.setLevel(logging.CRITICAL) """ fmt = logging.Formatter( '%(asctime)s - %(filename)s:[%(lineno)s] - [%(levelname)s] - %(message)s' ) curr_time = time.strftime( "%Y-%m-%d" ) self .LogFileName = '. \\ Logs \\ log' + curr_time + '.log' # "a" to append the logs in same file, "w" to generate new logs and delete old one fh = logging.FileHandler( self .LogFileName , mode = "a" ) fh.set...

Excel file operations in Python

 Below is the code which will demonstrate the Excel file operations in Python import openpyxl def getRowCount (path , sheetName): workbook = openpyxl.load_workbook(path) sheet = workbook[sheetName] return sheet.max_row def getColCount (path , sheetName): workbook = openpyxl.load_workbook(path) sheet = workbook[sheetName] return sheet.max_column def getCellData (path , sheetName , rowNum , colNum): workbook = openpyxl.load_workbook(path) sheet = workbook[sheetName] return sheet.cell( row =rowNum , column =colNum).value def setCellData (path , sheetName , rowNum , colNum , data): workbook = openpyxl.load_workbook(path) sheet = workbook[sheetName] sheet.cell( row =rowNum , column =colNum).value = data workbook.save(path) path = "..//excel//testdata.xlsx" sheetName = "LoginTest" rows = getRowCount(path , sheetName) cols = getColCount(path , sheetName) print (rows , "---" , cols) print (getCellData(path , shee...

Read Excel file data in Python

 Below is the code to Read Excel file data in Python import openpyxl def get_data (sheetName): workbook = openpyxl.load_workbook( "..//excel//testdata.xlsx" ) sheet = workbook[sheetName] totalrows = sheet.max_row totalcols = sheet.max_column mainList = [] for i in range ( 2 , totalrows + 1 ): dataList = [] for j in range ( 1 , totalcols + 1 ): data = sheet.cell( row =i , column =j).value dataList.insert(j , data) mainList.insert(i , dataList) return mainList

SFTP connection in Python

  import paramiko # create ssh client ssh_client = paramiko.SSHClient() # remote server credentials host = "host name here" username = "username here" password = "password here" port = PORT_NUMBER ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect( hostname =host , port =port , username =username , password =password) print ( 'connection established successfully' ) ftp = ssh_client.open_sftp() files = ftp.listdir() print ( "Listing all the files and Directory: " , files) # close the connection ftp.close() ssh_client.close()

Files I/O operations in Python

Below is the code for  Files I/O operations in Python import os import sys sys.path.extend( r'mention your local path here' ) print ( 'Get current working directory : ' , os.getcwd()) print ( 'File name : ' , os.path.basename(__file__)) print ( 'Directory Name: ' , os.path.dirname(__file__)) print ( 'Absolute path of file: ' , os.path.abspath(__file__)) print ( 'Absolute directory name: ' , os.path.dirname(os.path.abspath(__file__))) # Specify the directory you want to list directory_path = os.getcwd() # List all files and folders in the directory file_list = os.listdir(directory_path) # Get full paths full_paths = [os.path.join(directory_path , file) for file in file_list] print (full_paths)