50 Useful Python Scripts Free PDF
50 Useful Python Scripts Free PDF
md 12/05/2022
1 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
2 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Output
48. Excel to Python List of List Converter
Libraries Required
Usage
49. File Explorer Dialog Box in Python
1. Using tkinter
2. Using PyQt
50. File-Sharing-Bot
Summary
Installation
import json
if __name__ == '__main__':
try:
with open('input.json', 'r') as f:
data = json.loads(f.read())
output = ','.join([*data[0]])
for obj in data:
output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'
2. Password Generator
This simple Python project is using random and string package to generate a random string of a given
length.
import random
import string
total = string.ascii_letters + string.digits + string.punctuation
length = 16
password = "".join(random.sample(total, length))
print(password)
3 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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)
Installation
import requests as rq
from bs4 import BeautifulSoup
links = []
for link in soup.find_all("a"):
links.append(link.get("href"))
5. Image Watermarking
This project will take a photograph and put a watermark of your choice on it.
Installation
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':
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)
Installation
1. We need to install selenium and beautifulsoup4 using pip python package manager pip install
selenium beautifulsoup4 .
2. Then download chrome driver as per your chrome browser version and OS from here —
https://chromedriver.chromium.org/
3. You have to enter the chromedriver path asked by the program.
output = "output"
return res
6 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
def get_img_links(res):
soup = BeautifulSoup(res, "lxml")
imglinks = soup.find_all("img", src=True)
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
To run the following script you have to open the terminal into the script’s root directory and need to enter
the following command
python3 scrap-img.py
It will ask for the chrome driver path which you have just downloaded and a URL from which you want to
download images.
7 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
This python script displays a notice regarding the device’s battery percentage.
Installation
To run this script we need to download the psutil, py-notifier, and win10tost by running the following
commands.
1. psutil
> pip install psutil
2. pynotifier
> pip install py-notifier
3. win10toast
> pip install win10toast
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent
Notification(
title="Battery Low",
description=str(percent) + "% Battery remain!!",
duration=5, # Duration in seconds
).send()
Open your terminal into the root directory of your script file and run the following command
python3 battery.py
8 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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)
for m in range(1, localtime.tm_mon):
day = day + month_days(m, leap_year)
Simply open a terminal in the folder containing your script and enter the following command:
python3 calculate.py
import os
import shutil
os.chdir("E:\downloads")
#print(os.getcwd())
10 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Installation
This project only requires the Python standard library (more specifically, the csv, email, and smtplib
modules).
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()
11 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
message.set_content(body)
message['Subject'] = subject
if __name__ == "__main__":
send_mail()
emails.csv should include the email addresses to which the message should be sent.
credentials.txt should include your SMTP server login credentials, with your user name and password
on separate lines and no extra whitespace or decorations.
The project directory contains two sample files that you will almost certainly desire and need to alter.
python Send_emails.py
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()
12 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Installation
os.chdir(path)
list_images = os.listdir(path)
if "resize" not in list_images:
os.mkdir("resize")
13 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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, ""))
Installation
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary
script_name = sys.argv[0]
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
try:
14 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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):
'''
spliting the input csv/txt file according to the index provided
'''
data = pd.read_csv(self.file_name, header=None)
data.index += 1
15 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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()
##$ Prerequisites
pycryptodome 3.9.8
Python 3
16 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/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()
parser.add_argument("-p", "--path", help="absolute path to store
screenshot.", default=r"./images")
parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or
s (in seconds)", default='h')
parser.add_argument("-f", "--frequency", help="frequency for taking
screenshot per h/m/s.", default=1, type=int)
args = parser.parse_args()
sec = 0.
if args.type == 'h':
sec = 60 * 60 / args.frequency
elif args.type == 'm':
sec = 60 / args.frequency
17 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
sec = 1.
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")
How to run?
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")
Installation
18 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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
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
19 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
if __name__ == '__main__':
todo()
Running
Either run it from your code editor or Ide or type python todo.py [command] in your command line.
(instead of [command] add the desired command u want)
Commands
import requests
import json
import sys
from pprint import pprint
20 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
# 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",
"BHD : Bahraini Dinar,Bahrain Dinar",
"BIF : Burundian Franc,Burundi Franc",
"BMD : Bermudian Dollar,Bermuda Dollar",
"BND : Bruneian Dollar,Brunei Darussalam Dollar",
"BOB : Bolivian Bolíviano,Bolivia Bolíviano",
"BRL : Brazilian Real,Brazil Real",
"BSD : Bahamian Dollar,Bahamas Dollar",
"BTC : Bitcoin,BTC, XBT",
"BTN : Bhutanese Ngultrum,Bhutan Ngultrum",
"BWP : Botswana Pula,Botswana Pula",
"BYN : Belarusian Ruble,Belarus Ruble",
"BYR : Belarusian Ruble,Belarus Ruble",
"BZD : Belizean Dollar,Belize Dollar",
"CAD : Canadian Dollar,Canada Dollar",
"CDF : Congolese Franc,Congo/Kinshasa Franc",
"CHF : Swiss Franc,Switzerland Franc,Liechtenstein,Campione
d'Italia,Büsingen am Hochrhein",
"CLF : Chilean Unit of Account",
"CLP : Chilean Peso,Chile Peso",
"CNY : Chinese Yuan Renminbi,China Yuan Renminbi",
"COP : Colombian Peso,Colombia Peso",
"CRC : Costa Rican Colon,Costa Rica Colon",
"CUC : Cuban Convertible Peso,Cuba Convertible Peso",
"CUP : Cuban Peso,Cuba Peso",
21 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
)
if query == "Q":
sys.exit()
elif query == "SHOW":
pprint(currencies)
function1()
else:
qty, fromC, toC = query.split(" ")
fromC = fromC.upper()
toC = toC.upper()
qty = float(round(int(qty), 2))
amount = round(qty * fx[toC] / fx[fromC], 2)
print(f"{qty} of currency {fromC} amounts to {amount} of currency
{toC} today")
try:
function1()
except KeyError:
print("You seem to have inputted wrongly, retry!")
function1()
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
25 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
counter += 1
root = Tkinter.Tk()
root.title("Stopwatch")
start.pack(side='left')
stop.pack(side='left')
reset.pack(side='left')
root.mainloop()
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 = []
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:')
27 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
The CSV file may then be utilized for analysis, sorted by rating, and so on.
# Setting up session
s = requests.session()
# List contaiting all the films for which data has to be scraped from IMDB
films = []
28 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
print(URL)
# print(release)
try:
response = s.get(URL)
# print(response.status_code)
except Exception:
print("Try again with valid combination of tile and release year")
29 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
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)
Prerequisites
30 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
speech.save("voice.mp3")
os.system("voice.mp3")
try:
im = None
for root, dirs, files in os.walk("."):
for filename in files:
if filename.endswith('.jpg'):
im = Image.open(filename).convert("RGB")
im.save(filename.replace('jpg', 'png'), "png")
elif filename.endswith('.png'):
im = Image.open(filename).convert("RGB")
im.save(filename.replace('png', 'jpg'), "jpeg")
else:
print('dont have image to convert')
except IOError:
print('directory empty!')
sys.exit()
Installation
31 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
r.write(heading + "\n")
for i in wiki.select("p"):
# Optional Printing of text
# print(i.getText())
r.write(i.getText())
r.close()
print("File Saved as random_wiki.txt")
Website URLs should be listed one per line in the input file websites.txt.
A two-column report with the URL of each tested site and its state is included in the output file website
status.csv.
The script just checks for a 200 status code from the webserver.
Each time you run the utility, the result file will be overwritten.
import csv
import requests
# print(status_dict)
with open("website_status.csv", "w", newline="") as fw:
csv_writers = csv.writer(fw)
for key in status_dict.keys():
csv_writers.writerow([key, status_dict[key]])
if __name__ == "__main__":
main()
32 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Requirement
To run this script you need to have api key, to get an API key you first signup here
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(" Temperature (in kelvin unit) = " +
str(current_temperature) +
"\n atmospheric pressure (in hPa unit) = " +
str(current_pressure) +
"\n humidity (in percentage) = " +
str(current_humidiy) +
"\n description = " +
str(weather_description))
else:
print(" City Not Found ")
33 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
def backspace(entry):
input_len = len(entry.get())
entry.delete(input_len - 1)
def clear(entry):
entry.delete(0, END)
def calc(entry):
input_info = entry.get()
try:
output = str(eval(input_info.strip()))
except ZeroDivisionError:
popupmsg()
output = ""
clear(entry)
entry.insert(END, output)
def popupmsg():
popup = Tk()
popup.resizable(0, 0)
popup.geometry("120x100")
popup.title("Alert")
label = Label(popup, text="Cannot divide by 0 ! \n Enter valid values")
label.pack(side="top", fill="x", pady=10)
B1 = Button(popup, text="Okay", bg="#DDDDDD", command=popup.destroy)
B1.pack()
def cal():
root = Tk()
root.title("Calc")
root.resizable(0, 0)
entry_font = font.Font(size=15)
entry = Entry(root, justify="right", font=entry_font)
entry.grid(row=0, column=0, columnspan=4,
sticky=N + W + S + E, padx=5, pady=5)
cal_button_bg = '#FF6600'
34 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
num_button_bg = '#4B4B4B'
other_button_bg = '#DDDDDD'
text_fg = '#FFFFFF'
button_active_bg = '#C0C0C0'
35 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
root.mainloop()
if __name__ == '__main__':
cal()
1. edit app.py to add your sudoku matrix. (Fill 0 for empty cells.)
For example,
36 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
[[8, 1, 0, 0, 3, 0, 0, 2, 7],
[0, 6, 2, 0, 5, 0, 0, 9, 0],
[0, 7, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 6, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 2, 0, 0, 0, 4],
[0, 0, 8, 0, 0, 5, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 1, 0, 7, 5, 0],
[3, 8, 0, 0, 7, 0, 0, 4, 2]]
python3 app.py
This will give you output on the console. The output will contain the input sudoku matrix and the solved
sudoku matrix.
INPUT =>
8 1 0 | 0 3 0 | 0 2 7
0 6 2 | 0 5 0 | 0 9 0
0 7 0 | 0 0 0 | 0 0 0
---------------------
0 9 0 | 6 0 0 | 1 0 0
1 0 0 | 0 2 0 | 0 0 4
0 0 8 | 0 0 5 | 0 7 0
---------------------
0 0 0 | 0 0 0 | 0 8 0
0 2 0 | 0 1 0 | 7 5 0
3 8 0 | 0 7 0 | 0 4 2
OUTPUT =>
8 1 9 | 4 3 6 | 5 2 7
4 6 2 | 7 5 1 | 3 9 8
5 7 3 | 2 9 8 | 4 1 6
---------------------
2 9 4 | 6 8 7 | 1 3 5
1 5 7 | 9 2 3 | 8 6 4
6 3 8 | 1 4 5 | 2 7 9
---------------------
7 4 5 | 3 6 2 | 9 8 1
9 2 6 | 8 1 4 | 7 5 3
3 8 1 | 5 7 9 | 6 4 2
37 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
def printsudoku(sudoku):
print("\n\n")
for i in range(len(sudoku)):
line = ""
if i == 3 or i == 6:
print("---------------------")
for j in range(len(sudoku[i])):
if j == 3 or j == 6:
line += "| "
line += str(sudoku[i][j])+" "
print(line)
print("\n\n")
def findNextCellToFill(sudoku):
for x in range(9):
for y in range(9):
if sudoku[x][y] == 0:
return x, y
return -1, -1
38 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Usage
Encrypt file
Decrypt file
import os
import argparse
class Crypt:
def __init__(self):
encrypted = self.fernet.encrypt(input_data)
39 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
if __name__ == '__main__':
crypt = Crypt()
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-e', '--encrypt',
help='Encrpyt the file')
parser.add_argument('-d', '--decrypt',
help='Decrypt the file')
args = parser.parse_args()
if args.encrypt:
print(f'Input file: {args.encrypt}')
crypt.encrypt(args.encrypt)
elif args.decrypt:
print(f'Input file: {args.decrypt}')
crypt.decrypt(args.decrypt)
import geocoder
t=input("enter the location:")
g = geocoder.arcgis(t)
print(g.latlng)
40 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Can be run easily using command prompt (Python automated_email.py) -> login as you would for your
Gmail account( same email and password) -> find your way with the intuitive user-friendly menu (your
passwords and emails are only stored on your local device and no one has access to your information
otherwise!)
group = {}
print('\t\t ......LOGIN.....')
your_add = input('Enter your email address :')
password = input('Enter your email password for login:')
print('\n\n\n\n')
choice = 'y'
while(choice != '3' or choice != 'no'):
print("\n 1.Create a group\n2.Message a group\n3.Exit")
choice = input()
if choice == '1':
ch = 'y'
while(ch != 'n'):
gname = input('Enter name of group :')
group[gname] = input('Enter contact emails separated by a
single space :').rstrip()
ch = input('Add another....y/n? :').rstrip()
with open('groups.json', 'a') as f:
json.dump(group, f)
elif choice == '2':
gname = input('Enter name of group :')
try:
f = open('groups.json', 'r')
members = json.load(f)
41 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
f.close()
except:
print('Invalid group name. Please Create group first')
exit
members = members[gname].split()
msg = input('Enter message :')
for i in members:
try:
sendmail(your_add, i, msg, password)
except:
print("An unexpected error occured. Please try again
later...")
continue
else:
break
A chatbot (also known as a talkbot, chatterbot, Bot, IM bot, interactive agent, or Artificial Conversational
Entity) is a computer program or an artificial intelligence which conducts a conversation via auditory or
textual methods.
Start by running the below command on your UNIX terminal or Windows CMD:
$ python bash.py
import sys
try:
import aiml
except ImportError:
print('[!] Failed to import the module')
try:
select = raw_input('[*] Attempt to auto-install aiml? [Y/n')
except KeyboardInterrupt:
print('\n[!] User Cancel')
sys.exit(5)
if select.strip().lower()[0] == 'y':
print('[*] Trying to Install aiml... ')
sys.stdout.flush()
try:
import pip
pip.main(['install', '-q', 'aiml'])
import aiml
print('Finished')
except Exception:
42 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
kern = aiml.Kernel()
kern.learn('load.xml')
kern.respond('load aiml b')
while True:
print(kern.respond(raw_input('Type your Message >>')))
How to use
or
The default pair is Bitcoin to Malaysian Ringgit, to change that, click here to find out what tickers are
available and change XBTMYR in line 9.
import tkinter as tk
from tkinter import ttk
import urllib.request
import json
import time
def get_luno():
# to change ticker pair, look at here
https://api.mybitx.com/api/1/tickers
req = urllib.request.urlopen("https://api.mybitx.com/api/1/ticker?
pair=XBTMYR")
x = json.loads(req.read().decode("utf-8"))
43 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
req.close()
return x
def refresh_price():
aLable.configure(text="Ask price: RM " + get_luno()["ask"])
bLable.configure(text="Time: " +
str(time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(get_luno()["timestamp"]/1000 + 28800))))
win = tk.Tk()
win.title("Bitcoin price in MYR")
win.mainloop()
username = "username"
password = getpass.getpass("Password:")
problem = 'TEST'
code = """
#include <iostream>
int main(void) {
char c, d=10;
while(std::cin.get(c) && (c!='2' || d!='4') && std::cout.put(d))
d=c;
}
"""
browser = webdriver.Firefox()
browser.get('https://www.codechef.com')
44 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
nameElem = browser.find_element_by_id('edit-name')
nameElem.send_keys(username)
passElem = browser.find_element_by_id('edit-pass')
passElem.send_keys(password)
browser.find_element_by_id('edit-submit').click()
browser.get("https://www.codechef.com/submit/" + problem)
time.sleep(20)
browser.find_element_by_id("edit_area_toggle_checkbox_edit-
program").click()
inputElem = browser.find_element_by_id('edit-program')
inputElem.send_keys(code)
browser.find_element_by_id("edit-submit").click()
38. Checksum
This script can generate checksums from md5, sha1, sha224, sha256, sha384, and sha512. Additionally, for
another layer of secret, it can create signed checksums using HMAC and a provided secret. Lastly, to
provide actual value to the script it can also verify if a checksum matches the file it was generated from.
Examples:
Generate a signature
Verify a checksum
Verify a signature
45 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
import os
import sys
import hmac
import base64
import hashlib
import argparse
def main():
description = "Checksum tool to generate, sign, and verify"
46 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-g", "--generate", dest="generate",
action="store_true", help="Generates checksum")
parser.add_argument("-s", "--sign", dest="sign", default=None,
help="Signs input using HMAC")
parser.add_argument("-H", "--hash", dest="hash", default="md5",
help="Hash method (md5, sha1, sha224, sha256, sha384, sha512)")
parser.add_argument("-v", "--verify", dest="verify", default=None,
help="Checksum or signature used to verify against file / stdin")
parser.add_argument("-f", "--file", dest="file",
type=argparse.FileType("r"), default=sys.stdin,
help="File / stdin to create checksum, make signature, or verify
from")
arguments = parser.parse_args()
if __name__ == "__main__":
main()
Requirement
47 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Usage
$ virtualenv crypto-env
$ source crypto-env/bin/activate
$ pip3 install -r requirements.txt
$ python CryptoConverter.py
def digit_pressed(self):
button = self.sender()
self.new_label = self.label_1.text() + button.text()
if '.' in self.new_label:
self.label_1.setText(str(self.new_label))
else:
self.label_1.setText(str(int(self.new_label)))
def decimal_point(self):
48 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
if '.' in self.label_1.text():
pass
else:
self.label_1.setText(self.label_1.text() + '.')
def del_digit(self):
self.new_label = self.new_label[:-1]
self.label_1.setText(self.new_label)
def convert_fun(self):
try:
if len(self.new_label) == 0:
self.label_1.setText('0')
self.label_2.setText('0')
if '.' in self.new_label:
self.result = float(self.new_label) * self.api(self.cur1,
self.cur2)
self.result = round(self.result, 2)
self.label_2.setText(str(self.result))
else:
self.result = int(self.new_label) * self.api(self.cur1,
self.cur2)
self.result = round(self.result, 2)
self.label_2.setText(str(self.result))
except (KeyError, ValueError):
pass
except requests.exceptions.ConnectionError:
print('Please verify your internet connection!')
if __name__ == '__main__':
app = QApplication([])
app.setApplicationName("CryptoConverter")
window = MainWindow()
app.exec_()
49 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
Requirements
$ python cryptocurrency-prices.py
#!python3
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from colorama import init, Fore, Back, Style
import sys
import os
#for bitcoin
if asset == 'btc':
price = soup.find('span',{'class':'price'}).text #bitcoin works
faster with the price class
return float(price.replace(",",""))
#asset choice
asset = input('Abbreviation of the asset: ')
url = 'https://cryptowat.ch/assets/' + asset
50 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
#catching the NoneType AttributeError error for coins that cant be found
try:
price = get_price()
except AttributeError:
print("The asset doesn't exist or it's not supported!")
sys.exit()
#visual
if sys.platform == 'win32':
os.system('cls')
else:
os.system('clear')
#since the last price must be something from the start its set to 0
price = 0
#loop
while True:
Libraries Required
Usage
Example
51 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
import sys
from PIL import Image
from PIL.ExifTags import TAGS
image_file = sys.argv[1]
image_name = image_file.split(".")[0]
try:
image = Image.open(image_file)
except IOError:
print("Error in loading image!!")
sys.exit(1)
bw_image = image.convert('L')
bw_image.save("bw_"+image_name+".png")
How to run
python3 cricbuzz_scrap.py
quote_page = 'http://www.cricbuzz.com/cricket-match/live-scores'
page = urlopen(quote_page)
soup = BeautifulSoup(page,'html.parser')
update=[]
print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
*-*-*-*-*-*-*-*-*-*')
52 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
for i in range(len(update)):
print(i+1),
print(update[i])
print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
*-*-*-*-*-*-*-*-*-*')
Requirements
$ python main.py
#!python3
# -*- coding: utf-8 -*-
import openpyxl
import sys
#inputs
print("This programme writes the data in any Comma-separated value file
(such as: .csv or .data) to a Excel file.")
print("The input and output files must be in the same directory of the
python file for the programme to work.\n")
csv_name = input("Name of the CSV file for input (with the extension): ")
sep = input("Seperator of the CSV file: ")
excel_name = input("Name of the excel file for output (with the extension):
")
sheet_name = input("Name of the excel sheet for output: ")
53 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
except:
print("File Error!")
sys.exit()
#to write the next line column number is set to 1 and row number is
increased by 1
column = 1
row += 1
import requests
def get_temperature(json_data):
temp_in_celcius = json_data['main']['temp']
return temp_in_celcius
def get_weather_type(json_data):
weather_type = json_data['weather'][0]['description']
return weather_type
def get_wind_speed(json_data):
wind_speed = json_data['wind']['speed']
return wind_speed
54 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
def main():
api_address = 'https://api.openweathermap.org/data/2.5/weather?
q=Sydney,au&appid=a10fd8a212e47edf8d946f26fb4cdef8&q='
city = input("City Name : ")
units_format = "&units=metric"
final_url = api_address + city + units_format
json_data = requests.get(final_url).json()
weather_details = get_weather_data(json_data, city)
# print formatted data
print(weather_details)
main()
#!/usr/bin/python3
import argparse
import os
def path():
parse = argparse.ArgumentParser(
add_help=True, description="Organize your files to different
directories according to their type")
parse.add_argument('directory_path', type=str, default='./',
help="The absolute path to the directory")
return parse.parse_args().directory_path
55 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
for d in directories:
if os.listdir(d) is None:
os.removedirs(d)
else:
print("Exiting")
os.sys.exit(0)
A simple script that Excel files with a similar table structure from a given path as input and creates a unified
excel workbook.
Libraries Required
Usage
A sample script ‘Combine excel files into 1.py’ has been provided to show the usage of the Excel Merger.
When the script is run, it will ask for the name of the Unified Workbook and the path of the folder
containing the excel files that need to be merged.
# You can replace these with your own headers for the table
headers = ['Nume', 'Prenume', 'Titlu', 'Editura', 'Cota', 'Pret', 'An']
# Unified excel name
workbook_name = input('Unified Workbook name ')
book = Workbook()
sheet = book.active
# Specify path
path = input('Path: ')
# Get all files from folder
files = os.listdir(path)
for file in files:
rows = reader(file)
for row in rows:
sheet.append(row)
book.save(filename=workbook_name)
View extended info about your public IP address from the terminal.
Run program
python extended_ip_address_info.py
Output
{
"ip": "xxx.xxx.xxx.xxx",
"city": "A_city",
"hostname": "host.isp-website.com",
"region": "A_region",
"country": "Country code",
"loc": "coordinates",
"org": "AS-number ISP-name",
"postal": "postal-code",
"timezone": "Europe/City",
"readme": "https://ipinfo.io/missingauth"
}
#!/bin/python
# -*- coding: utf-8 -*-
buffer = BytesIO()
c = pycurl.Curl() #curl
c.setopt(c.HTTPHEADER, header) #header
c.setopt(c.URL, 'https://ipinfo.io/json') #URL
c.setopt(c.WRITEDATA, buffer)
58 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
body = buffer.getvalue()
# Body is a byte string.
# We have to know the encoding in order to print it to a text file
# such as standard output.
print(body.decode('iso-8859-1'))
Libraries Required
Usage
A sample script excel_to_list_usage.py has been provided to show the usage of the ExcelToList. It
reads the excel and its sheet, and prints the list of lists.
import xlrd
import sys
class ExcelToList():
def convert(self):
converted_list = []
inputexcel = xlrd.open_workbook(self.file)
inputsheet = inputexcel.sheet_by_name(self.sheet)
numberofrows = inputsheet.nrows
numberofcols = inputsheet.ncols
start_row,start_col = 0,0
for current_row in range(start_row,numberofrows):
currentlist = []
for current_col in range(start_col,numberofcols):
currentlist.append(inputsheet.cell(current_row,current_col).value)
converted_list.append(currentlist)
return converted_list
59 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
1. Using tkinter
$ python select_file_tk.py
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
2. Using PyQt
Install PyQt5
$ python select_file_pyqt.py
def select_files(directory_location=None):
qtapp = QApplication([directory_location])
qtwgt = QtWidgets.QWidget()
filenames, _ = QFileDialog.getOpenFileNames(qtwgt)
return filenames
def main():
filenames = select_files()
print("You selected:\n", "\n".join(filename for filename in filenames))
if __name__ == "__main__":
main()
60 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
50. File-Sharing-Bot
File-Sharing telegram Bot developed in Python It is like a centralized file repository where authorized users
can share files and files are available to all the users. Functionalities and commands can be seen using
the/help command. This bot can be directly hosted on Heroku.
logger = logging.getLogger(__name__)
61 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
file.
\nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last
sent file.
\nSend /mkdir folder_name to create a Folder.
'''
update.message.reply_text(reply)
bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'),
timeout = 100)
else:
update.message.reply_text("File not Found.")
new_file = bot.get_file(file_id)
message = update.message.text.split(" ")
path = message[-1]
if len(path) < 1:
update.message.reply_text("Enter Path correctly.")
else:
new_file.download(os.getcwd()+'/'+path)
update.message.reply_text("File Stored.")
63 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
TOKEN = os.environ['TOKEN']
updater = Updater(TOKEN)
#admin functionalities
dp.add_handler(CommandHandler("adduser", add_user))
dp.add_handler(CommandHandler("showuser", show_user))
dp.add_handler(CommandHandler("removeUser", remove_user))
dp.add_handler(CommandHandler("remove", remove))
dp.add_handler(CommandHandler("rmdir", rmdir))
64 / 65
50-useful-python-scripts-free-pdf-download.md 12/05/2022
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
Summary
In this article, I have discussed 50 Python scripts or 50 mini-projects that you can create to brush up on your
Python skills. I hope these will help you learn something new. Clap 👏 on this post to learn more posts from
this series of posts soon.
Thank you for reading this article, don’t forget to follow me on Medium or Twitter to read more articles like
this. You can also share this story with your friends if you find it helpful for others.
Buy Me A Coffee
65 / 65