Python utility scripts that can automate various tasks

Here are some examples of simple Python utility scripts that can automate various tasks:

1. File Renamer:

This script allows you to rename multiple files in a specific directory with a new name and extension.

import os

def rename_files(directory, new_name, extension):
    for filename in os.listdir(directory):
        if filename.endswith(extension):
            os.rename(os.path.join(directory, filename),
                      os.path.join(directory, new_name + extension))
    print("Files have been renamed successfully.")

rename_files("/path/to/directory", "new_name", ".txt")

2. CSV to Excel Converter:

This script can convert CSV files to Excel files.

import pandas as pd

def csv_to_excel(csv_file, excel_file):
    df = pd.read_csv(csv_file)
    df.to_excel(excel_file, index=False)
    print("Conversion complete.")

csv_to_excel("data.csv", "data.xlsx")

3. Website Scraper:

This script can scrape data from a website and save it to a file.

import requests
from bs4 import BeautifulSoup

def scrape_website(url, file):
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
    with open(file, "w") as f:
        f.write(soup.prettify())
    print("Scraping complete.")

scrape_website("https://www.example.com", "data.txt")

4. File Backup:

This script can copy files from one location to another and save it as a backup.

import shutil
import datetime

def backup_files(src, dst):
    now = datetime.datetime.now()
    backup_folder = dst + now.strftime("%Y-%m-%d %H:%M:%S")
    shutil.copytree(src, backup_folder)
    print("Backup complete.")

backup_files("/path/to/src", "/path/to/dst")

5. Find and Replace:

This script can find and replace a specific word or phrase in all files in a specific directory.

import os

def find_and_replace(directory, find, replace):
    for foldername, subfolders, filenames in os.walk(directory):
        for filename in filenames:
            file_path = os.path.join(foldername, filename)
            with open(file_path) as f:
                s = f.read()
            s = s.replace(find, replace)
            with open(file_path, "w") as f:
                f.write(s)
    print("Find and Replace complete.")

find_and_replace("/path/to/directory", "find", "replace")

These are just a few examples of the many things you can do with Python utility scripts. You can also use libraries like os, shutil, pandas, beautiful

Leave a Reply