
25 Ways to Use Python Scripts
Python is a versatile and widely-used programming language that can be applied to various domains, from web development and data analysis to automation and machine learning. In this article, we’ll explore 25 ways to use Python scripts to improve your productivity, automate tasks, and enhance your overall workflow.
Automation
1. Automate System Tasks
Use Python’s subprocess
module to run system commands and automate repetitive tasks, such as backing up files or updating dependencies.
“`python
import subprocess
Run a command in the terminal
subprocess.run([“ls”, “-l”])
“`
2. Schedule Tasks with Cron
Utilize Python’s schedule
library to schedule tasks to run at specific times or intervals, making it easier to automate repetitive jobs.
“`python
import schedule
import time
def job():
# Code to execute when the job runs
print(“Hello World!”)
Schedule the job to run every 10 minutes
schedule.every(10).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
“`
Data Analysis and Science
3. Work with Pandas DataFrames
Use Python’s pandas
library to efficiently work with structured data, such as CSV files or Excel spreadsheets.
“`python
import pandas as pd
Load a CSV file into a DataFrame
df = pd.read_csv(“data.csv”)
Manipulate the data
df[“column”] = df[“column”].astype(str)
Save the updated DataFrame to a new CSV file
df.to_csv(“updated_data.csv”, index=False)
“`
4. Visualize Data with Matplotlib
Utilize Python’s matplotlib
library to create static, animated, and interactive visualizations of your data.
“`python
import matplotlib.pyplot as plt
Create a simple plot
plt.plot([1, 2, 3])
plt.xlabel(“X-axis”)
plt.ylabel(“Y-axis”)
plt.title(“Example Plot”)
plt.show()
“`
Web Development
5. Build Web Applications with Flask
Use Python’s flask
library to create lightweight web applications that are perfect for prototyping or small-scale projects.
“`python
from flask import Flask
app = Flask(name)
@app.route(“/”)
def hello_world():
return “Hello, World!”
if name == “main“:
app.run()
“`
6. Use Django for Web Development
Utilize Python’s django
library to build robust and scalable web applications with a high-level framework.
“`python
from django.http import HttpResponse
def hello_world(request):
return HttpResponse(“Hello, World!”)
Run the development server
if name == “main“:
from django.core.management import execute_from_commandline
execute_from_commandline(["manage.py", "runserver"])
“`
Machine Learning and AI
7. Train Machine Learning Models with Scikit-Learn
Use Python’s scikit-learn
library to train and evaluate machine learning models, such as linear regression or decision trees.
“`python
from sklearn.linear_model import LinearRegression
Create a linear regression model
model = LinearRegression()
Train the model on some data
X_train = [[1], [2], [3]]
y_train = [4, 5, 6]
model.fit(X_train, y_train)
Make predictions
X_test = [[7], [8], [9]]
predictions = model.predict(X_test)
“`
8. Use TensorFlow for Deep Learning
Utilize Python’s tensorflow
library to build and train deep learning models, such as neural networks or convolutional neural networks.
“`python
import tensorflow as tf
Create a simple neural network
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(64, activation=”relu”, input_shape=(784,)),
tf.keras.layers.Dense(32, activation=”relu”),
tf.keras.layers.Dense(10, activation=”softmax”)
])
Compile the model
model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.SparseCategoricalCrossentropy())
“`
Miscellaneous
9. Create Chatbots with NLTK
Use Python’s nltk
library to create simple chatbots that can understand and respond to user input.
“`python
import nltk
Load a lexicon
lexicon = {“hello”: “greetings”, “goodbye”: “farewell”}
Process user input
user_input = nltk.word_tokenize(“Hello!”)
Match the input against the lexicon
if user_input[0] in lexicon:
print(lexicon[user_input[0]])
“`
10. Automate File and Folder Management with os
Utilize Python’s os
library to automate file and folder management tasks, such as creating directories or deleting files.
“`python
import os
Create a new directory
os.mkdir(“new_directory”)
Delete an existing file
os.remove(“existing_file.txt”)
“`
11. Work with SQLite Databases
Use Python’s sqlite3
library to create and interact with SQLite databases, perfect for simple data storage needs.
“`python
import sqlite3
Connect to the database
conn = sqlite3.connect(“example.db”)
Create a new table
c = conn.cursor()
c.execute(“CREATE TABLE IF NOT EXISTS example (id INTEGER PRIMARY KEY)”)
Insert some data
c.execute(“INSERT INTO example VALUES (?, ?)”, (1, “hello”))
Commit the changes
conn.commit()
Close the connection
conn.close()
“`
12. Parse HTML and XML with BeautifulSoup
Utilize Python’s beautifulsoup4
library to parse HTML and XML documents, making it easy to extract data from web pages or other structured content.
“`python
from bs4 import BeautifulSoup
Parse an HTML document
soup = BeautifulSoup(“…“, “html.parser”)
Extract some data
data = soup.find(“title”).text
print(data)
“`
13. Use OpenCV for Computer Vision
Utilize Python’s opencv-python
library to build computer vision applications, such as image processing or object detection.
“`python
import cv2
Load an image
img = cv2.imread(“image.jpg”)
Convert the image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Apply some filters
filtered_img = cv2.GaussianBlur(gray_img, (3, 3), 0)
“`
14. Automate Email Tasks with smtplib
Use Python’s smtplib
library to automate email tasks, such as sending emails or logging into email accounts.
“`python
import smtplib
Send an email
server = smtplib.SMTP(“smtp.example.com”, 587)
server.starttls()
server.login(“username@example.com”, “password”)
server.sendmail(“from@example.com”, “to@example.com”, “Hello, World!”)
“`
15. Work with RSS Feeds
Utilize Python’s feedparser
library to parse and work with RSS feeds, making it easy to read news or updates from online sources.
“`python
import feedparser
Parse an RSS feed
feed = feedparser.parse(“https://example.com/rss”)
Extract some data
entries = feed.entries
for entry in entries:
print(entry.title)
“`
16. Automate Windows Tasks with win32api
Use Python’s win32api
library to automate tasks on a Windows system, such as sending keyboard shortcuts or navigating the file system.
“`python
import win32api
Send some keyboard shortcuts
win32api.keybd_event(win32api.VK_F1, 0)
time.sleep(1)
win32api.keybd_event(win32api.VK_F1, 0)
Navigate the file system
win32api.ShellExecuteW(None, “open”, “C:\Windows\explorer.exe”, None, None, 5)
“`
17. Work with Excel Spreadsheets
Utilize Python’s xlrd
and xlwt
libraries to create and interact with Excel spreadsheets, perfect for working with structured data.
“`python
import xlrd
from xlwt import Workbook
Load an Excel spreadsheet
wb = xlrd.open_workbook(“example.xlsx”)
sh = wb.sheet_by_index(0)
Extract some data
data = sh.cell_value(1, 2)
Create a new workbook
wb = Workbook()
ws = wb.add_sheet(‘Sheet’)
“`
18. Automate Linux Tasks with pexpect
Use Python’s pexpect
library to automate tasks on a Linux system, such as sending commands or navigating the terminal.
“`python
from pexpect import spawn
Send some commands
child = spawn(“bash”)
child.expect(‘$’)
child.sendline(‘echo Hello World!’)
“`
19. Work with Word Documents
Utilize Python’s python-docx
library to create and interact with Microsoft Word documents, perfect for working with structured text.
“`python
import docx
Load a Word document
doc = docx.Document(“example.docx”)
Extract some data
data = doc.paragraphs[0].text
print(data)
“`
20. Automate Tasks with TaskScheduler
Use Python’s pytask
library to create and interact with tasks in the Windows Task Scheduler, perfect for automating system tasks.
“`python
import pytask
Create a new task
task = pytask.Task()
task.action = ‘C:\Windows\System32\cmd.exe /c echo Hello World!’
“`
21. Work with PDF Documents
Utilize Python’s PyPDF2
library to create and interact with PDF documents, perfect for working with structured text.
“`python
import PyPDF2
Load a PDF document
pdf = PyPDF2.PdfFileReader(“example.pdf”)
Extract some data
data = pdf.getPage(0).extractText()
print(data)
“`
22. Automate Tasks with Cron
Use Python’s schedule
library to create and interact with cron jobs, perfect for automating system tasks.
“`python
import schedule
Run a task every minute
schedule.every(1).minutes.do(something)
while True:
schedule.run_pending()
time.sleep(1)
“`
23. Work with Outlook Emails
Utilize Python’s win32com.client
library to create and interact with Microsoft Outlook emails, perfect for working with structured email data.
“`python
import win32com.client
Create a new outlook application
outlook = win32com.client.Dispatch(“Outlook.Application”)
Get the MAPI namespace
mapi = outlook.GetNamespace(‘MAPI’)
Log in to an account
account = mapi.Logon(None, None)
“`
24. Automate Tasks with PowerShell
Use Python’s subprocess
library to create and interact with PowerShell scripts, perfect for automating system tasks.
“`python
import subprocess
Run a powershell script
process = subprocess.Popen([“powershell.exe”, “-ExecutionPolicy Bypass -File ‘example.ps1′”])
“`
25. Work with Google Sheets
Utilize Python’s gspread
library to create and interact with Google Spreadsheets, perfect for working with structured data.
“`python
import gspread
Open a spreadsheet
doc = gspread.open(“example”)
Get the first worksheet
worksheet = doc.worksheet[0]
Extract some data
data = worksheet.get_all_records()
“`
Note that some of these examples may require additional setup or configuration to work properly. Additionally, be sure to check the documentation for each library to ensure you are using them correctly and responsibly.