25 Awesome Python Scripts
25 Awesome Python Scripts
md 19/01/2022
Buy Me A Coffee
import json
if __name__ == '__main__':
try:
with open('input.json', 'r') as f:
data = json.loads(f.read())
1 / 26
python-snippets.md 19/01/2022
output = ','.join([*data[0]])
for obj in data:
output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'
2. Password Generator
import random
import string
total = string.ascii_letters + string.digits + string.punctuation
length = 16
password = "".join(random.sample(total, length))
print(password)
import os
text = input("input text : ")
path = input("path : ")
# os.chdir(path)
def getfiles(path):
f = 0
os.chdir(path)
files = os.listdir()
# print(files)
for file_name in files:
abs_path = os.path.abspath(file_name)
if os.path.isdir(abs_path):
getfiles(abs_path)
if os.path.isfile(abs_path):
f = open(file_name, "r")
if text in f.read():
f = 1
print(text + " found in ")
final_path = os.path.abspath(file_name)
print(final_path)
return True
if f == 1:
print(text + " not found! ")
return False
getfiles(path)
2 / 26
python-snippets.md 19/01/2022
import requests as rq
from bs4 import BeautifulSoup
5. Image Watermarking
import os
from PIL import Image
def
watermark_photo(input_image_path,watermark_image_path,output_image_path):
base_image = Image.open(input_image_path)
watermark = Image.open(watermark_image_path).convert("RGBA")
# add watermark to your image
position = base_image.size
newsize = (int(position[0]*8/100),int(position[0]*8/100))
# print(position)
watermark = watermark.resize(newsize)
# print(newsize)
# return watermark
new_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20
# create a new transparent image
transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))
# paste the original image
transparent.paste(base_image,(0,0))
# paste the watermark image
transparent.paste(watermark,new_position,watermark)
image_mode = base_image.mode
print(image_mode)
if image_mode == 'RGB':
3 / 26
python-snippets.md 19/01/2022
transparent = transparent.convert(image_mode)
else:
transparent = transparent.convert('P')
transparent.save(output_image_path,optimize=True,quality=100)
print("Saving"+output_image_path+"...")
if not os.path.isdir("output"):
os.mkdir("output")
c = 1
for f in files:
if os.path.isfile(os.path.abspath(f)):
if f.endswith(".png") or f.endswith(".jpg"):
watermark_photo(f,watermark,"output/"+f)
output = "output"
return res
def get_img_links(res):
soup = BeautifulSoup(res, "lxml")
imglinks = soup.find_all("img", src=True)
4 / 26
python-snippets.md 19/01/2022
return imglinks
img_data = rq.get(img_link).content
with open(output + "\\" + str(index + 1) + extension, "wb+") as f:
f.write(img_data)
f.close()
except Exception:
pass
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent
Notification(
5 / 26
python-snippets.md 19/01/2022
title="Battery Low",
description=str(percent) + "% Battery remain!!",
duration=5, # Duration in seconds
).send()
import time
from calendar import isleap
year = int(age)
month = year * 12 + localtime.tm_mon
day = 0
leap_year = judge_leap_year(localtime.tm_year)
6 / 26
python-snippets.md 19/01/2022
import os
import shutil
os.chdir("E:\downloads")
#print(os.getcwd())
7 / 26
python-snippets.md 19/01/2022
import csv
from email.message import EmailMessage
import smtplib
def get_credentials(filepath):
with open("credentials.txt", "r") as f:
email_address = f.readline()
email_pass = f.readline()
return (email_address, email_pass)
def send_mail():
s = smtplib.SMTP("smtp.gmail.com", 587)
email_address, email_pass = get_credentials("./credentials.txt")
login(email_address, email_pass, s)
# message to be sent
subject = "Welcome to Python"
body = """Python is an interpreted, high-level,
general-purpose programming language.\n
Created by Guido van Rossum and first released in 1991,
Python's design philosophy emphasizes code readability\n
with its notable use of significant whitespace"""
message = EmailMessage()
message.set_content(body)
message['Subject'] = subject
8 / 26
python-snippets.md 19/01/2022
if __name__ == "__main__":
send_mail()
def get_hostname_IP():
hostname = input("Please enter website address(URL):")
try:
print (f'Hostname: {hostname}')
print (f'IP: {socket.gethostbyname(hostname)}')
except socket.gaierror as error:
print (f'Invalid Hostname, error raised is {error}')
get_hostname_IP()
os.chdir(path)
list_images = os.listdir(path)
if "resize" not in list_images:
os.mkdir("resize")
import subprocess
data = (
subprocess.check_output(["netsh", "wlan", "show", "profiles"])
.decode("utf-8")
.split("\n")
)
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
for i in profiles:
results = (
subprocess
.check_output(["netsh", "wlan", "show", "profile", i, "key=clear"])
.decode("utf-8")
.split("\n")
)
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in
b]
try:
print("{:<30}| {:<}".format(i, results[0]))
except IndexError:
print("{:<30}| {:<}".format(i, ""))
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary
script_name = sys.argv[0]
10 / 26
python-snippets.md 19/01/2022
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
try:
url = sys.argv[1]
driver.get(url)
page_width = driver.execute_script('return document.body.scrollWidth')
page_height = driver.execute_script('return
document.body.scrollHeight')
driver.set_window_size(page_width, page_height)
driver.save_screenshot('screenshot.png')
driver.quit()
print("SUCCESS")
except IndexError:
print('Usage: %s URL' % script_name)
import sys
import os
import shutil
import pandas as pd
class Split_Files:
'''
Class file for split file program
'''
def __init__(self, filename, split_number):
'''
Getting the file name and the split index
Initializing the output directory, if present then truncate it.
Getting the file extension
'''
self.file_name = filename
self.directory = "file_split"
self.split = int(split_number)
if os.path.exists(self.directory):
shutil.rmtree(self.directory)
os.mkdir(self.directory)
if self.file_name.endswith('.txt'):
self.file_extension = '.txt'
else:
self.file_extension = '.csv'
self.file_number = 1
def split_data(self):
11 / 26
python-snippets.md 19/01/2022
'''
spliting the input csv/txt file according to the index provided
'''
data = pd.read_csv(self.file_name, header=None)
data.index += 1
split_frame = pd.DataFrame()
output_file = f"{self.directory}/split_file{self.file_number}
{self.file_extension}"
if __name__ == '__main__':
file, split_number = sys.argv[1], sys.argv[2]
sp = Split_Files(file, split_number)
sp.split_data()
12 / 26
python-snippets.md 19/01/2022
# Use the newly generated AES object to decrypt the encrypted ciphertext
decrypttext = mydecrypt.decrypt(ciphertext[16:])
# output
file_out = open("encrypted.bin", "wb")
file_out.write(ciphertext[16:])
file_out.close()
import os
import argparse
import pyautogui
import time
parser = argparse.ArgumentParser()
args = parser.parse_args()
sec = 0.
if args.type == 'h':
sec = 60 * 60 / args.frequency
elif args.type == 'm':
sec = 60 / args.frequency
13 / 26
python-snippets.md 19/01/2022
if os.path.isdir(args.path) != True:
os.mkdir(args.path)
try:
while True:
t = time.localtime()
current_time = time.strftime("%H_%M_%S", t)
file = current_time + ".jpg"
image = pyautogui.screenshot(os.path.join(args.path,file))
print(f"{file} saved successfully.\n")
time.sleep(sec)
except KeyboardInterrupt:
print("End of script by user interrupt")
try:
menu = int(input("Choose an option: \n 1. Decimal to binary \n 2.
Binary to decimal\n Option: "))
if menu < 1 or menu > 2:
raise ValueError
if menu == 1:
dec = int(input("Input your decimal number:\nDecimal: "))
print("Binary: {}".format(bin(dec)[2:]))
elif menu == 2:
binary = input("Input your binary number:\n Binary: ")
print("Decimal: {}".format(int(binary, 2)))
except ValueError:
print ("please choose a valid option")
import click
@click.group()
@click.pass_context
def todo(ctx):
'''Simple CLI Todo App'''
ctx.ensure_object(dict)
#Open todo.txt – first line contains latest ID, rest contain tasks and
IDs
14 / 26
python-snippets.md 19/01/2022
with open('./todo.txt') as f:
content = f.readlines()
#Transfer data from todo.txt to the context
ctx.obj['LATEST'] = int(content[:1][0])
ctx.obj['TASKS'] = {en.split('```')[0]:en.split('```')[1][:-1] for en
in content[1:]}
@todo.command()
@click.pass_context
def tasks(ctx):
'''Display tasks'''
if ctx.obj['TASKS']:
click.echo('YOUR TASKS\n**********')
#Iterate through all the tasks stored in the context
for i, task in ctx.obj['TASKS'].items():
click.echo('• ' + task + ' (ID: ' + i + ')')
click.echo('')
else:
click.echo('No tasks yet! Use ADD to add one.\n')
@todo.command()
@click.pass_context
@click.option('-add', '--add_task', prompt='Enter task to add')
def add(ctx, add_task):
'''Add a task'''
if add_task:
#Add task to list in context
ctx.obj['TASKS'][ctx.obj['LATEST']] = add_task
click.echo('Added task "' + add_task + '" with ID ' +
str(ctx.obj['LATEST']))
#Open todo.txt and write current index and tasks with IDs
(separated by " ``` ")
curr_ind = [str(ctx.obj['LATEST'] + 1)]
tasks = [str(i) + '```' + t for (i, t) in ctx.obj['TASKS'].items()]
with open('./todo.txt', 'w') as f:
f.writelines(['%s\n' % en for en in curr_ind + tasks])
@todo.command()
@click.pass_context
@click.option('-fin', '--fin_taskid', prompt='Enter ID of task to finish',
type=int)
def done(ctx, fin_taskid):
'''Delete a task by ID'''
#Find task with associated ID
if str(fin_taskid) in ctx.obj['TASKS'].keys():
task = ctx.obj['TASKS'][str(fin_taskid)]
#Delete task from task list in context
del ctx.obj['TASKS'][str(fin_taskid)]
click.echo('Finished and removed task "' + task + '" with id ' +
str(fin_taskid))
#Open todo.txt and write current index and tasks with IDs
(separated by " ``` ")
if ctx.obj['TASKS']:
curr_ind = [str(ctx.obj['LATEST'] + 1)]
15 / 26
python-snippets.md 19/01/2022
if __name__ == '__main__':
todo()
import requests
import json
import sys
from pprint import pprint
# The below 4 lines bring out the value of currency from the api at
fixer.io. I had to register there, the key is unique to me.
url = "http://data.fixer.io/api/latest?
access_key=33ec7c73f8a4eb6b9b5b5f95118b2275"
data = requests.get(url).text
data2 = json.loads(data) #brings whether request was successful,timestamp
etc
fx = data2["rates"]
currencies = [
"AED : Emirati Dirham,United Arab Emirates Dirham",
"AFN : Afghan Afghani,Afghanistan Afghani",
"ALL : Albanian Lek,Albania Lek",
"AMD : Armenian Dram,Armenia Dram",
"ANG : Dutch Guilder,Netherlands Antilles
Guilder,Bonaire,Curaçao,Saba,Sint Eustatius,Sint Maarten",
"AOA : Angolan Kwanza,Angola Kwanza",
"ARS : Argentine Peso,Argentina Peso,Islas Malvinas",
"AUD : Australian Dollar,Australia Dollar,Christmas Island,Cocos
(Keeling) Islands,Norfolk Island,Ashmore and Cartier Islands,Australian
Antarctic Territory,Coral Sea Islands,Heard Island,McDonald
Islands,Kiribati,Nauru",
"AWG : Aruban or Dutch Guilder,Aruba Guilder",
"AZN : Azerbaijan Manat,Azerbaijan Manat",
"BAM : Bosnian Convertible Mark,Bosnia and Herzegovina Convertible
Mark",
"BBD : Barbadian or Bajan Dollar,Barbados Dollar",
"BDT : Bangladeshi Taka,Bangladesh Taka",
"BGN : Bulgarian Lev,Bulgaria Lev",
16 / 26
python-snippets.md 19/01/2022
Islands,Tokelau",
"OMR : Omani Rial,Oman Rial",
"PAB : Panamanian Balboa,Panama Balboa",
"PEN : Peruvian Sol,Peru Sol",
"PGK : Papua New Guinean Kina,Papua New Guinea Kina",
"PHP : Philippine Peso,Philippines Peso",
"PKR : Pakistani Rupee,Pakistan Rupee",
"PLN : Polish Zloty,Poland Zloty",
"PYG : Paraguayan Guarani,Paraguay Guarani",
"QAR : Qatari Riyal,Qatar Riyal",
"RON : Romanian Leu,Romania Leu",
"RSD : Serbian Dinar,Serbia Dinar",
"RUB : Russian Ruble,Russia Ruble,Tajikistan,Abkhazia,South Ossetia",
"RWF : Rwandan Franc,Rwanda Franc",
"SAR : Saudi Arabian Riyal,Saudi Arabia Riyal",
"SBD : Solomon Islander Dollar,Solomon Islands Dollar",
"SCR : Seychellois Rupee,Seychelles Rupee",
"SDG : Sudanese Pound,Sudan Pound",
"SEK : Swedish Krona,Sweden Krona",
"SGD : Singapore Dollar,Singapore Dollar",
"SHP : Saint Helenian Pound,Saint Helena Pound",
"SLL : Sierra Leonean Leone,Sierra Leone Leone",
"SOS : Somali Shilling,Somalia Shilling",
"SRD : Surinamese Dollar,Suriname Dollar",
"STN : Sao Tomean Dobra,São Tomé and Príncipe Dobra",
"SVC : Salvadoran Colon,El Salvador Colon",
"SYP : Syrian Pound,Syria Pound",
"SZL : Swazi Lilangeni,eSwatini Lilangeni",
"THB : Thai Baht,Thailand Baht",
"TJS : Tajikistani Somoni,Tajikistan Somoni",
"TMT : Turkmenistani Manat,Turkmenistan Manat",
"TND : Tunisian Dinar,Tunisia Dinar",
"TOP : Tongan Pa'anga,Tonga Pa'anga",
"TRY : Turkish Lira,Turkey Lira,North Cyprus",
"TTD : Trinidadian Dollar,Trinidad and Tobago Dollar,Trinidad,Tobago",
"TWD : Taiwan New Dollar,Taiwan New Dollar",
"TZS : Tanzanian Shilling,Tanzania Shilling",
"UAH : Ukrainian Hryvnia,Ukraine Hryvnia",
"UGX : Ugandan Shilling,Uganda Shilling",
"USD : US Dollar,United States Dollar,America,American Samoa,American
Virgin Islands,British Indian Ocean Territory,British Virgin
Islands,Ecuador,El Salvador,Guam,Haiti,Micronesia,Northern Mariana
Islands,Palau,Panama,Puerto Rico,Turks and Caicos Islands,United States
Minor Outlying Islands,Wake Island,East Timor",
"UYU : Uruguayan Peso,Uruguay Peso",
"UZS : Uzbekistani Som,Uzbekistan Som",
"VEF : Venezuelan Bolívar,Venezuela Bolívar",
"VND : Vietnamese Dong,Viet Nam Dong",
"VUV : Ni-Vanuatu Vatu,Vanuatu Vatu",
"WST : Samoan Tala,Samoa Tala",
"XAF : Central African CFA Franc BEAC,Communauté Financière
Africaine (BEAC) CFA Franc BEAC,Cameroon,Central African
Republic,Chad,Congo/Brazzaville,Equatorial Guinea,Gabon",
"XAG : Silver Ounce,Silver",
19 / 26
python-snippets.md 19/01/2022
try:
function1()
except KeyError:
print("You seem to have inputted wrongly, retry!")
function1()
20 / 26
python-snippets.md 19/01/2022
counter = 0
running = False
def counter_label(label):
def count():
if running:
global counter
# To manage the intial delay.
if counter == 0:
display = 'Ready!'
else:
tt = datetime.utcfromtimestamp(counter)
string = tt.strftime('%H:%M:%S')
display = string
label['text'] = display
root = Tkinter.Tk()
root.title("Stopwatch")
import zipfile
import sys
import os
# Declare the function to return all file paths of the particular directory
def retrieve_file_paths(dir_name):
# setup file paths variable
file_paths = []
22 / 26
python-snippets.md 19/01/2022
if __name__ == "__main__":
path = sys.argv[1]
if os.path.isdir(path):
files_path = retrieve_file_paths(path)
# print the list of files to be zipped
print('The following list of files will be zipped:')
for file_name in files_path:
print(file_name)
zip_dir(path, files_path)
elif os.path.isfile(path):
print('The %s will be zipped:' % path)
zip_file(path)
else:
print('a special file(socket,FIFO,device file), please input file
or dir')
# Setting up session
s = requests.session()
# List contaiting all the films for which data has to be scraped from IMDB
films = []
23 / 26
python-snippets.md 19/01/2022
names = []
ratings = []
genres = []
# print(response.status_code)
24 / 26
python-snippets.md 19/01/2022
except Exception:
print("Try again with valid combination of tile and release year")
items=[]
driver=webdriver.Chrome(r"C:/Users/hp/Anaconda3/chromedriver.exe")
driver.get('https://www.youtube.com/watch?v=iFPMz36std4')
driver.execute_script('window.scrollTo(1, 500);')
driver.execute_script('window.scrollTo(1, 3000);')
username_elems = driver.find_elements_by_xpath('//*[@id="author-text"]')
comment_elems = driver.find_elements_by_xpath('//*[@id="content-text"]')
for username, comment in zip(username_elems, comment_elems):
item = {}
item['Author'] = username.text
item['Comment'] = comment.text
items.append(item)
filename = 'C:/Users/hp/Desktop/commentlist.csv'
with open(filename, 'w', newline='', encoding='utf-8') as f:
w = csv.DictWriter(f,['Author','Comment'])
w.writeheader()
for item in items:
w.writerow(item)
25 / 26
python-snippets.md 19/01/2022
Buy Me A Coffee
26 / 26