0% found this document useful (0 votes)
0 views36 pages

Top 10 Python Automation Scripts That You Should Try Once

Uploaded by

jmanzungu2820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views36 pages

Top 10 Python Automation Scripts That You Should Try Once

Uploaded by

jmanzungu2820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Top 10 Python Automation Scripts That

You Should Try Once

by Saptorshee Nag

June 29, 2024

Reading Time: 22 mins read

Python offers many features and it is easy to learn, but, sometimes


developers have to code repetitive tasks and snippets again and
again. Thankfully, there are some of these tasks that can be
automated, freeing up our time to concentrate on other tasks that
truly require our time and effort.

Today, we will explore 10 Python Automation Scripts that will help


you perform automation tasks across various aspects of development,
and save up your precious time.

0 of 34 secondsVolume 0%

Automation in Python
Python automation means using the language to write
scripts, programs, or other tools that carry out automatic
processes without the need for human
interaction. Automation can be used for several processes including
file management, web scraping, data analysis, system monitoring,
and more.
Here are the common automation tasks used in Python:

 File Management:
 Reading/Writing Files: Automate tasks such as reading

from or writing to files.


 File Organization: Rename, move, or delete files based
on certain criteria.
 Web Scraping:
 Data Extraction: Automate the process of collecting

data from websites.


 Monitoring: Check websites for updates or changes.
 Data Processing:
 Data Cleaning: Automate the cleaning and preparation

of data for analysis.


 Data Transformation: Convert data from one format to
another.
 System Administration:
 Task Scheduling: Automate repetitive system tasks,

such as backups or software updates.


 Resource Monitoring: Check system resources and log
statistics.
 API Interaction:
 Data Retrieval: Automate interactions with APIs to fetch

data.
 Automated Reporting: Collect data from various
sources and generate reports.
 Testing:
 Unit Testing: Automate the testing of code to ensure it

works as expected.
 Integration Testing: Test interactions between
different parts of a system.
Thus, automation is a crucial aspect of programming with Python
nowadays and has many applications and use cases across diverse
fields.

How to perform Automation in


Python?
Although it may seem difficult, you can automate an operation if you
follow these instructions and have a basic understanding of Python.
Writing an automation script is simple.
1. Identify the Task
 Define the problem: Understand what you want to automate.
 Break down the task: Divide it into smaller, manageable
steps.
2. Choose the Right Tools and Libraries
Select appropriate libraries based on the task. Here are some
common tasks and their corresponding libraries:

 File Management: os, shutil, glob, pathlib


 Web Scraping: requests, BeautifulSoup, Scrapy, Selenium
 Data Processing: pandas, numpy
 System Administration: subprocess, psutil, schedule
 API Interaction: requests, httpx
 Testing: unittest, pytest
3. Write the Script
Develop a Python script that uses the selected libraries to automate
the task. Use the right libraries and functions while scripting.

4. Test the Script


Run the script in a controlled environment to ensure it works
correctly and handles exceptions. Make sure you test it properly and
figure out possible errors and issues.

5. Schedule the Script


Use scheduling tools or services to run your script at desired
intervals. You can update and fix your code if it’s not functioning
correctly or if there are some instances of incorrect outcomes. This
phase allows you to add functionality to your code if you would like
to in the future.

10 Python Automation Scripts To


Boost Your Efficiency
These 10 Python automation scripts can be used to automate
repetitive processes, as demonstrated by these amazing examples.
1. File Management: Organize Files by
Extension
This script provides a straightforward way to organize files by their
extensions. It’s easy to customize and extend for more complex file
management needs. For more sophisticated file management tasks,
you can consider incorporating additional libraries or writing more
complex logic.

Python
1
import os
2
import shutil
3

4
def organize_files_by_extension(directory):
5
"""
6
Organizes files in the given directory by their extensions.
7

8
:param directory: Path to the directory to organize.
9
"""
10
# Iterate through all files in the directory
11
for filename in [Link](directory):
12
# Ignore directories
13
if [Link]([Link](directory, filename)):
14
continue
15

16
# Extract file extension
17
ext = [Link]('.')[-1]
18
ext_dir = [Link](directory, ext)
19

20
# Create a directory for the extension if it doesn't exist
21
[Link](ext_dir, exist_ok=True)
22

23
# Construct full file paths
24
src_path = [Link](directory, filename)
25
dest_path = [Link](ext_dir, filename)
26

27
# Move file to the new directory
28
[Link](src_path, dest_path)
29
print(f'Moved {filename} to {ext_dir}')
30

31
# Example usage
32
organize_files_by_extension('/path/to/your/directory')

Here’s how you can run the script:


Install Python: Ensure you have Python installed on your system.
Save the Script: Save the script to a .py file, e.g., organize_files.py.
Run the Script: Open a terminal and run the script with the
directory path you want to organize.
python organize_files.py
Thus, this script helps organize files in a directory by moving them
into folders named after their file extensions.

2. Web Scraping: Extract Titles from a Web


Page
This script provides a simple way to scrape and extract article titles
from a web page. It can be extended to handle more complex
scenarios such as dealing with dynamic content or saving data in
different formats. For web scraping projects, always check the target
website’s [Link] file and terms of service to ensure compliance
with their policies.

Python
1
import requests
2
from bs4 import BeautifulSoup
3

4
def extract_article_titles(url):
5
"""
6
Extracts article titles from a web page.
7
8
:param url: URL of the web page to scrape.
9
:return: List of article titles.
10
"""
11
try:
12
# Fetch the content of the URL
13
response = [Link](url)
14
response.raise_for_status() # Raise an HTTPError if the HTTP request returned an
unsuccessful status code
15
except [Link] as e:
16
print(f"Error fetching the URL: {e}")
17
return []
18

19
# Parse the HTML content
20
soup = BeautifulSoup([Link], '[Link]')
21

22
# Extract article titles
23
titles = []
24
for header in soup.find_all(['h1', 'h2', 'h3']): # Adjust tags as needed
25
title = header.get_text(strip=True)
26
if title: # Only add non-empty titles
27
[Link](title)
28

29
return titles
30

31
# Example usage
32
url = '[Link]
33
titles = extract_article_titles(url)
34
for i, title in enumerate(titles, start=1):
35
print(f'{i}. {title}')

Here’s how you can run the script:


Save the Script: Save the script as extract_titles.py.
Run the Script: Open a terminal and run the script with Python:
python extract_titles.py
This is a Python automation script for web scraping that extracts
article titles from a web page using the requests and BeatifulSoup
libraries. Web scraping involves fetching and parsing the HTML
content of web pages to extract useful data.

3. System Administration: Check Disk


Usage
This Python automation script designed for system administration
that checks disk usage. This script monitors the available disk space
on a system and alerts if the free space falls below a specified
threshold. It provides a basic yet effective way to monitor disk usage.

Python
1
import shutil
2
import os
3
import platform
4

5
def check_disk_usage(threshold):
6
"""
7
Checks the disk usage and alerts if free space is below the given threshold.
8

9
:param threshold: The minimum free space percentage allowed before an alert is
raised.
10
"""
11
# Get disk usage statistics
12
total, used, free = shutil.disk_usage('/')
13

14
# Calculate percentage of free space
15
free_percent = free / total * 100
16
17
# Print the disk usage details
18
print(f"Total: {total / (1024**3):.2f} GB")
19
print(f"Used: {used / (1024**3):.2f} GB")
20
print(f"Free: {free / (1024**3):.2f} GB ({free_percent:.2f}%)")
21

22
# Check if free space is below the threshold
23
if free_percent < threshold:
24
print(f"Warning: Only {free_percent:.2f}% free space left!")
25
else:
26
print(f"Sufficient disk space available ({free_percent:.2f}% free).")
27

28
# Example usage
29
threshold = 20 # Set threshold for free space percentage
30
check_disk_usage(threshold)

Here’s how you can run the script:


Save the Script: Save the script as check_disk_usage.py.
Run the Script: Open a terminal and run the script with Python:
python check_disk_usage.py
By customizing and extending this script, you can create a more
robust system administration tool that suits your specific needs.
Always consider additional features like logging, notifications, and
multi-platform support based on your use case.

4. API Interaction: Fetch Weather Data


Now let’s explore a Python automation script that fetches weather
data from an API. This script uses an API to get current weather
information for a specified location and displays the details.

It provides a foundation for various enhancements, including


handling multiple cities, saving data, using command-line arguments,
and creating a GUI. Always ensure that the API key is kept secure and
comply with the terms of service of the weather API provider.

Python
1
import requests
2

3
def fetch_weather(api_key, city):
4
"""
5
Fetches and prints weather data for a given city using OpenWeatherMap API.
6

7
:param api_key: Your OpenWeatherMap API key.
8
:param city: City name to fetch the weather for.
9
"""
10
# API endpoint
11
url = '[Link]
12

13
# Parameters to be sent with the request
14
params = {
15
'q': city,
16
'appid': api_key,
17
'units': 'metric' # Use 'imperial' for Fahrenheit
18
}
19

20
try:
21
# Send GET request
22
response = [Link](url, params=params)
23
response.raise_for_status() # Raise an HTTPError for bad responses
24

25
# Parse JSON response
26
data = [Link]()
27

28
# Extract weather information
29
city_name = data['name']
30
weather = data['weather'][0]['description']
31
temp = data['main']['temp']
32
feels_like = data['main']['feels_like']
33
humidity = data['main']['humidity']
34
wind_speed = data['wind']['speed']
35

36
# Print weather information
37
print(f"Weather in {city_name}:")
38
print(f" Description: {weather}")
39
print(f" Temperature: {temp}°C")
40
print(f" Feels Like: {feels_like}°C")
41
print(f" Humidity: {humidity}%")
42
print(f" Wind Speed: {wind_speed} m/s")
43

44
except [Link] as e:
45
print(f"Error fetching weather data: {e}")
46
except KeyError as e:
47
print(f"Error parsing weather data: {e}")
48

49
# Example usage
50
api_key = 'your_api_key_here' # Replace with your OpenWeatherMap API key
51
city = 'London'
52
fetch_weather(api_key, city)

Here’s how you can run the script:


Save the Script: Save the script as fetch_weather.py.
Run the Script: Open a terminal and run the script with Python:
python fetch_weather.py
5. Data Processing: Clean a CSV File
Let’s walk through a Python automation script that processes and
cleans a CSV file. This script will handle common cleaning tasks such
as removing missing values, converting data types, renaming
columns, and filtering rows.

Python
1
import pandas as pd
2

3
def clean_csv(input_file, output_file):
4
"""
5
Cleans a CSV file by removing missing values, converting data types, renaming
columns,
6
and filtering rows.
7
8
:param input_file: Path to the input CSV file.
9
:param output_file: Path to the output cleaned CSV file.
10
"""
11
# Load CSV data into DataFrame
12
df = pd.read_csv(input_file)
13

14
# Print original data summary
15
print("Original Data Summary:")
16
print([Link]())
17
print([Link](), "\n")
18

19
# Remove rows with missing values
20
[Link](inplace=True)
21

22
# Convert data types (example: converting 'date' to datetime)
23
# Ensure to adjust the column names and types as per your CSV
24
if 'date' in [Link]:
25
df['date'] = pd.to_datetime(df['date'], errors='coerce')
26

27
# Rename columns (example: renaming 'old_name' to 'new_name')
28
# Ensure to adjust the column names as per your CSV
29
[Link](columns={'old_name': 'new_name'}, inplace=True)
30

31
# Filter rows (example: keep only rows where 'column' > value)
32
# Adjust the filter conditions as per your needs
33
if 'column' in [Link]:
34
df = df[df['column'] > value]
35

36
# Print cleaned data summary
37
print("Cleaned Data Summary:")
38
print([Link]())
39
print([Link](), "\n")
40

41
# Save cleaned data to new CSV file
42
df.to_csv(output_file, index=False)
43
print(f"Cleaned data saved to {output_file}")
44

45
# Example usage
46
input_file = '[Link]'
47
output_file = 'cleaned_data.csv'
48
clean_csv(input_file, output_file)
49

Here’s how you can run the script:


Save the Script: Save the script as clean_csv.py.
Prepare CSV Files: Ensure you have the input CSV file (e.g.,
[Link]).
Run the Script: Open a terminal and run the script with Python.
python clean_csv.py
This Python script provides a framework for cleaning CSV files, which
is a common task in data processing workflows. By extending and
customizing it, you can adapt the script to fit specific data cleaning
needs. The use of pandas allows for powerful and flexible data
manipulation, making it ideal for such tasks.

6. Battery Indicator
Creating a Python automation script for a battery indicator typically
involves reading the battery status and providing feedback through
an appropriate interface, such as a console output, GUI application, or
physical indicator (like an LED).

Here’s a simple Python Automation Script that reads the battery


status from a system file and prints the status to the console. This can
serve as a basis for more complex applications involving GUIs or
hardware interfacing.
Python
1
import time
2

3
def read_battery_status(file_path):
4
"""
5
Reads the battery status from the specified file.
6

7
:param file_path: Path to the battery status file.
8
:return: Battery charge level as an integer percentage.
9
"""
10
try:
11
with open(file_path, 'r') as file:
12
capacity = [Link]().strip()
13
return int(capacity)
14
except (FileNotFoundError, ValueError) as e:
15
print(f"Error reading battery status: {e}")
16
return None
17

18
def print_battery_status(charge_level):
19
"""
20
Prints the battery status to the console.
21

22
:param charge_level: Current battery charge level as an integer percentage.
23
"""
24
if charge_level is not None:
25
print(f"Battery level: {charge_level}%")
26

27
# Example usage
28
BATTERY_FILE_PATH = '/sys/class/power_supply/BAT0/capacity' # Example path for
Linux
29

30
try:
31
while True:
32
charge_level = read_battery_status(BATTERY_FILE_PATH)
33
print_battery_status(charge_level)
34
[Link](60) # Check every 60 seconds
35
36
except KeyboardInterrupt:
37
print("Exiting...")

Here’s how you can run the script:


Save the Script: Save the script as battery_indicator.py.
Run the Script: Open a terminal and run the script with Python:
python battery_indicator.py
This Python script provides a foundational example of how to
automate battery status monitoring and feedback. It can be adapted
and extended based on specific needs such as integrating with GUIs,
triggering alerts, or interfacing with physical indicators. Always
consider the platform-specific details and permissions required when
accessing system files or hardware resources.

7. Convert PDF to Image


Converting PDF files to images using Python can be achieved using
various libraries. One popular choice is PyMuPDF (also known as fitz),
which allows you to extract pages from a PDF and save them as
images.

Below is a Python script that uses PyMuPDF to convert each page of a


PDF file to an image file (PNG format). This script will read a PDF file,
extract each page as an image, and save it.

Python
1
import fitz # PyMuPDF
2

3
def pdf_to_images(pdf_file, output_folder):
4
"""
5
Converts each page of a PDF file to an image (PNG).
6

7
:param pdf_file: Path to the PDF file.
8
:param output_folder: Path to the output folder where images will be saved.
9
"""
10
# Open the PDF file
11
pdf_document = [Link](pdf_file)
12

13
# Iterate through each page of the PDF
14
for page_num in range(len(pdf_document)):
15
# Get the page
16
page = pdf_document.load_page(page_num)
17

18
# Convert page to image (PNG)
19
image = page.get_pixmap()
20

21
# Save image to output folder
22
image_path = f"{output_folder}/page_{page_num + 1}.png"
23
[Link](image_path)
24
print(f"Page {page_num + 1} saved as {image_path}")
25

26
# Close the PDF document
27
pdf_document.close()
28

29
# Example usage
30
if __name__ == "__main__":
31
pdf_file = "[Link]" # Replace with your PDF file path
32
output_folder = "output_images" # Replace with your desired output folder
33

34
# Create output folder if it doesn't exist
35
import os
36
if not [Link](output_folder):
37
[Link](output_folder)
38

39
# Convert PDF to images
40
pdf_to_images(pdf_file, output_folder)

Here’s how you can use it:


Prepare your PDF file:
Place the PDF file that you want to convert into the same directory as
your Python script. For this example, let’s assume your PDF file is
named ‘[Link]’.

Copy the Script:


Copy the Python script provided earlier into a new file. You can use
any text editor or an integrated development environment (IDE) such
as Visual Studio Code, PyCharm, or IDLE.

Modify Script Parameters (Optional)


 Replace ‘[Link]’ with the name of your PDF file.

 Modify ‘output_images’ to the desired name of the output folder


where images will be saved.

Run the script:


Open a terminal or command prompt and navigate to the directory
where your Python script ‘pdf_to_image.py’ and ‘[Link]’ are
located. Run the script by typing:

python pdf_to_image.py

This script provides a basic framework for converting PDF files to


images using Python and PyMuPDF. Depending on your
requirements, you can extend it further to include additional
functionalities such as image format conversion, page range selection,
or integration with GUI frameworks for user interaction.

8. Email Scheduler
Creating an email scheduler using Python involves automating the
process of sending emails at scheduled intervals or specific times.
This can be accomplished by combining Python’s smtplib for sending
emails and schedule or datetime for scheduling tasks.
This script will allow you to communicate with your contacts easily
and say good-bye to sending emails by hand. Emails can be
automatically scheduled and sent at a specified time with this script.

Python
1
import smtplib
2
import schedule
3
import time
4
from [Link] import MIMEMultipart
5
from [Link] import MIMEText
6
from datetime import datetime
7

8
def send_email(subject, body, to_email):
9
"""
10
Sends an email with the specified subject and body.
11

12
:param subject: Subject of the email.
13
:param body: Body content of the email.
14
:param to_email: Recipient email address.
15
"""
16
from_email = "your_email@[Link]" # Replace with your email address
17
password = "your_password" # Replace with your email password
18

19
# Create the email content
20
message = MIMEMultipart()
21
message['From'] = from_email
22
message['To'] = to_email
23
message['Subject'] = subject
24

25
[Link](MIMEText(body, 'plain'))
26

27
try:
28
# Connect to the SMTP server
29
server = [Link]('[Link]', 587) # Replace with your SMTP server
and port
30
[Link]() # Secure the connection
31
[Link](from_email, password)
32

33
# Send the email
34
server.send_message(message)
35
print(f"Email sent to {to_email} at {[Link]()}")
36

37
# Disconnect from the server
38
[Link]()
39
except Exception as e:
40
print(f"Failed to send email: {e}")
41

42
def schedule_email():
43
"""
44
Schedules the email to be sent.
45
"""
46
subject = "Scheduled Email"
47
body = "This is an automatically scheduled email."
48
to_email = "recipient@[Link]" # Replace with recipient email address
49

50
send_email(subject, body, to_email)
51
52
# Schedule the email to be sent every day at a specific time
53
schedule_time = "14:00" # Replace with your desired schedule time (24-hour format)
54
[Link]().[Link](schedule_time).do(schedule_email)
55

56
print(f"Email scheduler started. Will send emails every day at {schedule_time}.")
57

58
try:
59
while True:
60
# Run pending scheduled tasks
61
schedule.run_pending()
62
[Link](1)
63
except KeyboardInterrupt:
64
print("Email scheduler stopped.")

Here’s how you can run the script:


Save the Script: Save the script as email_scheduler.py.
Edit the Script:
 Replace “your_email@[Link]” and “your_password” with
your actual email and password.
 Replace “[Link]” with your SMTP server address
and port (e.g., [Link], port 587 for Gmail).
 Replace “recipient@[Link]” with the recipient’s email
address.
 Modify the schedule_time as needed.
Run the Script: Open a terminal or command prompt, navigate to
the directory containing email_scheduler.py, and run:
python email_scheduler.py
By following these steps, you can set up a Python script to schedule
and send emails automatically. This can be extended with more
sophisticated scheduling logic, handling multiple recipients, or using
templated email content.

9. Image Optimizer
This Python automation script lets you easily edit and modify your
images like an expert with only a few clicks, eliminating the need for
pricey programmes or sophisticated editing equipment.

This script optimises photos by use the well-liked Pillow module. To


crop, resize, flip, rotate, compress, blur, sharpen, alter brightness and
contrast, and add filters to an image, it makes use of the Python
Imaging Library (PIL).

Python
1
from PIL import Image
2
import os
3

4
def optimize_image(input_path, output_path, quality=85, max_width=None,
max_height=None):
5
"""
6
Optimize an image by resizing and adjusting its quality.
7

8
:param input_path: Path to the input image file.
9
:param output_path: Path to save the optimized image file.
10
:param quality: Image quality for the output (1 to 100).
11
:param max_width: Maximum width for resizing (optional).
12
:param max_height: Maximum height for resizing (optional).
13
"""
14
try:
15
# Open an image file
16
with [Link](input_path) as img:
17
print(f"Optimizing {input_path}...")
18

19
# Resize the image if max_width or max_height is specified
20
if max_width or max_height:
21
[Link]((max_width, max_height), [Link])
22

23
# Save the image with the specified quality
24
[Link](output_path, optimize=True, quality=quality)
25
print(f"Saved optimized image to {output_path}")
26

27
except Exception as e:
28
print(f"Error optimizing {input_path}: {e}")
29

30
def optimize_images_in_directory(directory, output_directory, quality=85,
max_width=None, max_height=None):
31
"""
32
Optimize all images in the specified directory.
33

34
:param directory: Directory containing images to optimize.
35
:param output_directory: Directory to save optimized images.
36
:param quality: Image quality for the output (1 to 100).
37
:param max_width: Maximum width for resizing (optional).
38
:param max_height: Maximum height for resizing (optional).
39
"""
40
# Create the output directory if it doesn't exist
41
if not [Link](output_directory):
42
[Link](output_directory)
43

44
# Iterate through all files in the directory
45
for filename in [Link](directory):
46
input_path = [Link](directory, filename)
47
output_path = [Link](output_directory, filename)
48

49
# Check if the file is an image
50
if [Link]().endswith(('png', 'jpg', 'jpeg', 'gif', 'bmp')):
51
optimize_image(input_path, output_path, quality, max_width, max_height)
52

53
# Example usage
54
if __name__ == "__main__":
55
input_dir = "input_images" # Replace with your input directory
56
output_dir = "optimized_images" # Replace with your output directory
57
image_quality = 85 # Adjust quality as needed (1 to 100)
58
max_img_width = 800 # Replace with max width or None
59
max_img_height = 600 # Replace with max height or None
60
61
optimize_images_in_directory(input_dir, output_dir, quality=image_quality,
max_width=max_img_width, max_height=max_img_height)

Here’s how you can run the script:


Save the Script: Save the script as image_optimizer.py.
Prepare Directories: Create an input_images directory and place
your images there. Ensure the script has the correct paths for
input_dir and output_dir.
Run the Script: Open a terminal or command prompt, navigate to
the directory containing image_optimizer.py, and run:
python image_optimizer.py
This Python script provides a straightforward way to optimize images
by resizing and adjusting their quality. It’s flexible and can be easily
adapted to different requirements or integrated into larger systems.

10. Video Optimizer


Creating a Python automation script for video optimization involves
compressing video files to reduce their size while maintaining
quality. This is useful for reducing storage requirements, improving
streaming performance, and speeding up file transfers.

Below is an example using the ffmpeg tool, which is a powerful


multimedia framework for handling video, audio, and other
multimedia files and streams.

Python
1
import os
2
import subprocess
3

4
def optimize_video(input_path, output_path, resolution="1280x720", bitrate="1M"):
5
"""
6
Optimize a video file using ffmpeg.
7

8
:param input_path: Path to the input video file.
9
:param output_path: Path to save the optimized video file.
10
:param resolution: Resolution for the output video (e.g., '1280x720').
11
:param bitrate: Bitrate for the output video (e.g., '1M' for 1 Mbps).
12
"""
13
try:
14
print(f"Optimizing {input_path}...")
15

16
# Construct the ffmpeg command
17
command = [
18
'ffmpeg',
19
'-i', input_path,
20
'-vf', f'scale={resolution}',
21
'-b:v', bitrate,
22
'-c:a', 'copy',
23
output_path
24
]
25

26
# Run the command
27
[Link](command, check=True)
28
print(f"Saved optimized video to {output_path}")
29

30
except [Link] as e:
31
print(f"Error optimizing {input_path}: {e}")
32

33
def optimize_videos_in_directory(directory, output_directory, resolution="1280x720",
bitrate="1M"):
34
"""
35
Optimize all videos in the specified directory.
36

37
:param directory: Directory containing videos to optimize.
38
:param output_directory: Directory to save optimized videos.
39
:param resolution: Resolution for the output videos (e.g., '1280x720').
40
:param bitrate: Bitrate for the output videos (e.g., '1M' for 1 Mbps).
41
"""
42
# Create the output directory if it doesn't exist
43
if not [Link](output_directory):
44
[Link](output_directory)
45

46
# Iterate through all files in the directory
47
for filename in [Link](directory):
48
input_path = [Link](directory, filename)
49
output_path = [Link](output_directory, filename)
50

51
# Check if the file is a video
52
if [Link]().endswith(('mp4', 'mkv', 'mov', 'avi', 'flv', 'wmv', 'webm')):
53
optimize_video(input_path, output_path, resolution, bitrate)
54

55
# Example usage
56
if __name__ == "__main__":
57
input_dir = "input_videos" # Replace with your input directory
58
output_dir = "optimized_videos" # Replace with your output directory
59
video_resolution = "1280x720" # Replace with desired resolution (e.g., '1920x1080')
60
video_bitrate = "1M" # Replace with desired bitrate (e.g., '500K' for 500 kbps)
61

62
optimize_videos_in_directory(input_dir, output_dir, resolution=video_resolution,
bitrate=video_bitrate)

Here’s how you can run the script:


Save the Script: Save the script as video_optimizer.py.
Prepare Directories: Create an input_videos directory and place
your video files there. Ensure the script has the correct paths for
input_dir and output_dir.
Run the Script: Open a terminal or command prompt, navigate to
the directory containing video_optimizer.py, and run:
python video_optimizer.py
This will optimize videos from the input_videos directory and save
the optimized versions in the optimized_videos directory.

This Python script provides a straightforward way to optimize videos


using ffmpeg. It’s flexible and can be easily adapted to different
requirements or integrated into larger automation workflows. You
can modify it further to include additional features like logging, more
complex optimizations, or support for batch processing larger
collections of videos.

Conclusion
These Python Automation Scripts have been designed on a variety of
factors to give you the best automation experience across your daily
tasks and everyday projects.

You might also like