DEV Community

qing
qing

Posted on

8 Python Scripts That Will Make You Look Like a Senior Developer

Introduction to Senior-Level Python Scripts

As a Python developer, you're likely familiar with the basics of the language. However, to take your skills to the next level and become a senior developer, you need to be able to write efficient, readable, and well-structured code that solves real-world problems. In this article, we'll explore eight Python scripts that will help you achieve this goal.

Script 1: File Automation using shutil and os

The first script is a simple file automation tool that uses the shutil and os modules to move files from one directory to another based on their extension.

import os
import shutil

# Define the source and destination directories
src_dir = '/path/to/source/directory'
dst_dir = '/path/to/destination/directory'

# Define the file extensions to move
extensions = ['.txt', '.pdf', '.jpg']

# Iterate over the files in the source directory
for filename in os.listdir(src_dir):
    # Check if the file has one of the specified extensions
    if os.path.splitext(filename)[1] in extensions:
        # Move the file to the destination directory
        shutil.move(os.path.join(src_dir, filename), dst_dir)
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the shutil and os modules to interact with the file system, as well as the ability to specify multiple file extensions to move.

Script 2: API Wrapper using requests

The second script is an API wrapper that uses the requests library to make GET requests to a specified API endpoint.

import requests

class ApiWrapper:
    def __init__(self, base_url):
        self.base_url = base_url

    def get_data(self, endpoint):
        response = requests.get(self.base_url + endpoint)
        return response.json()

# Usage
api = ApiWrapper('https://api.example.com')
data = api.get_data('/users')
print(data)
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of object-oriented programming to create a reusable API wrapper class, as well as the ability to handle JSON responses from the API.

Script 3: Data Processing using pandas

The third script is a data processing tool that uses the pandas library to read a CSV file, filter the data, and write the results to a new CSV file.

import pandas as pd

# Read the CSV file
df = pd.read_csv('data.csv')

# Filter the data
df_filtered = df[df['age'] > 30]

# Write the filtered data to a new CSV file
df_filtered.to_csv('filtered_data.csv', index=False)
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the pandas library to efficiently process large datasets, as well as the ability to filter the data based on specific conditions.

Script 4: CLI Tool using argparse

The fourth script is a CLI tool that uses the argparse library to parse command-line arguments and perform a specified action.

import argparse

def main():
    parser = argparse.ArgumentParser(description='My CLI Tool')
    parser.add_argument('--name', help='Your name')
    args = parser.parse_args()

    print(f'Hello, {args.name}!')

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the argparse library to create a reusable and user-friendly CLI tool, as well as the ability to handle command-line arguments.

Script 5: Web Scraping Helper using beautifulsoup4

The fifth script is a web scraping helper that uses the beautifulsoup4 library to parse HTML pages and extract specific data.

import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    # Extract the title of the webpage
    title = soup.title.text
    return title

# Usage
url = 'https://www.example.com'
title = scrape_website(url)
print(title)
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the beautifulsoup4 library to parse HTML pages, as well as the ability to extract specific data from the webpage.

Script 6: System Utility using psutil

The sixth script is a system utility that uses the psutil library to monitor system resources such as CPU usage, memory usage, and disk usage.

import psutil

def get_system_info():
    cpu_usage = psutil.cpu_percent()
    memory_usage = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/').percent

    return cpu_usage, memory_usage, disk_usage

# Usage
cpu_usage, memory_usage, disk_usage = get_system_info()
print(f'CPU Usage: {cpu_usage}%')
print(f'Memory Usage: {memory_usage}%')
print(f'Disk Usage: {disk_usage}%')
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the psutil library to monitor system resources, as well as the ability to extract specific data such as CPU usage and memory usage.

Script 7: Data Visualization using matplotlib

The seventh script is a data visualization tool that uses the matplotlib library to create a line chart from a specified dataset.

import matplotlib.pyplot as plt

def visualize_data(data):
    plt.plot(data)
    plt.xlabel('X Axis')
    plt.ylabel('Y Axis')
    plt.title('Line Chart')
    plt.show()

# Usage
data = [1, 2, 3, 4, 5]
visualize_data(data)
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the matplotlib library to create a reusable and customizable data visualization tool, as well as the ability to extract specific data from the dataset.

Script 8: Logging Utility using logging

The eighth script is a logging utility that uses the logging library to log messages at different levels such as debug, info, warning, and error.

import logging

def configure_logging():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    return logger

# Usage
logger = configure_logging()
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
Enter fullscreen mode Exit fullscreen mode

What makes this script senior-level is the use of the logging library to create a reusable and customizable logging utility, as well as the ability to log messages at different levels.

Conclusion

In this article, we've explored eight Python scripts that will help you take your skills to the next level and become a senior developer. These scripts cover a range of topics including file automation, API wrappers, data processing, CLI tools, web scraping helpers, system utilities, data visualization, and logging utilities. By mastering these scripts, you'll be able to write efficient, readable, and well-structured code that solves real-world problems.

If you want to learn more about Python programming and stay up-to-date with the latest developments, be sure to follow me for more content. I'll be sharing more articles and tutorials on Python programming, as well as other topics related to software development and technology. Thanks for reading!


Found this useful? Follow me on Dev.to for more Python automation tips every week. Drop a comment below — I reply to every one!


🛠️ Recommended Tool

If you found this useful, check out Content Creator Ultimate Bundle (Save 33%) — $29.99 and designed for developers like you.

Get instant access to our best-selling AI Dev Boost, HTML Landing Page Templates, AI Prompts for Developers, and Python Automation Scripts Pack, perfect for content creators and marketers looking to elevate their game. This bundle is a must-have for anyone looking to create stunning content, build high-converting landing pages, and drive real results. With these tools, you'll be able to create engaging content, build beautiful landing pages, and boost your online presence.

Top comments (0)