Apakah kamu mencari bahasa pemrograman untuk membantu menjalankan tugas-tugas secara otomatis? Python adalah pilihan yang tepat! Dengan sintaks yang sederhana dan library yang lengkap, Python merupakan salah satu bahasa pemrograman terbaik untuk membuat skrip otomatisasi.
Baik kamu seorang programmer atau sekadar ingin mempermudah tugas sehari-hari, Python memiliki alat yang bisa membantumu. Dalam artikel ini, saya akan membagikan 10 script Python yang sering digunakan untuk menjalankan tugas secara otomatis agar kamu bisa menghemat waktu dan meningkatkan produktivitas.
1. Mengubah Nama File Bersamaan (Bulk Rename)
Merubah nama file satu persatu bisa sangat melelahkan. Dengan Python, kamu bisa melakukannya secara otomatis dalam hitungan detik.
import os
def bulk_rename(direktori, pola_nama_lama, pengganti):
for filename in os.listdir(direktori):
if pola_nama_lama in filename:
new_filename = filename.replace(pola_nama_lama, pengganti)
os.rename(os.path.join(direktori, filename), os.path.join(direktori, new_filename))
print(f"Renamed {filename} to {new_filename}")
folder = '/folder/yang/ingin/digunakan'
bulk_rename(folder, 'pola_lama', 'nama_baru')
2. Backup File Secara Otomatis
Buat cadangan file kamu secara teratur dengan modul shutil. Skrip ini menyalin file dari satu direktori ke direktori lain.
import shutil
import os
def backup_files(directory_sumber, directory_tujuan):
if not os.path.exists(directory_tujuan):
os.makedirs(directory_tujuan)
for file in os.listdir(directory_sumber):
full_file_name = os.path.join(directory_sumber, file)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, directory_tujuan)
print(f"Backed up {file} to {directory_tujuan}")
sumber = "/sumber/directory"
tujuan = "/tujuan/directory"
backup_files(sumber, tujuan)
3. Download File Dari Internet
Jika kamu perlu mengunduh banyak file sekaligus, gunakan library aiohttp agar proses download berjalan lebih efisien.
import aiohttp
import asyncio
import aiofiles
async def download_file(url, filename):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
async with aiofiles.open(filename, "wb") as file:
await file.write(await response.read())
print(f"Downloaded {filename}")
urls = {
"https://contohnya.com/file1.zip": "file1.zip",
"https://contohnya.com/file2.zip": "file2.zip",
}
async def download_all():
tasks = [download_file(url, filename) for url, filename in urls.items()]
await asyncio.gather(*tasks)
asyncio.run(download_all())
4. Otomatisasi Email Report
Kirim laporan rutin secara otomatis menggunakan library smtplib. Skrip ini memungkinkanmu mengirim email dari akun Gmail dengan mudah.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, body, to_email):
sender_email = 'youremail@gmail.com'
sender_password = 'yourpassword'
receiver_email = to_email
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
subject = 'Monthly Report'
body = 'Here is the monthly report.'
send_email(subject, body, 'receiver@example.com')
5. Web Scraping Untuk Mengumpulkan Data
Menggunakan aiohttp untuk async request membuat proses pengikisan web (web scraping) jauh lebih cepat dan efisien.
import aiohttp
import asyncio
from bs4 import BeautifulSoup
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def scrape(urls):
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
html_pages = await asyncio.gather(*tasks)
for html in html_pages:
soup = BeautifulSoup(html, 'html.parser')
print(soup.title.string)
urls = ['https://example.com/page1', 'https://example.com/page2']
asyncio.run(scrape(urls))
6. Posting ke Sosial Media
Otomatisasi postingan media sosial menggunakan library seperti Tweepy untuk Twitter.
import tweepy
def tweet(message):
consumer_key = "your_consumer_key"
consumer_secret = "your_consumer_secret"
access_token = "your_access_token"
access_token_secret = "your_access_token_secret"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
api.update_status(message)
print("Tweet sent successfully!")
tweet("Hello, world!")
7. Memonitor Up-time Situs
Pastikan situsmu selalu online dengan skrip sederhana menggunakan library requests.
import requests
import time
def check_website(url):
try:
response = requests.get(url)
if response.status_code == 200:
print(f"Website {url} is up!")
else:
print(f"Website {url} returned a status code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Error checking website {url}: {e}")
url = "https://example.com"
while True:
check_website(url)
time.sleep(3600) # Cek setiap jam
8. Bersih-bersih File
Jaga direktorimu tetap rapi dengan menghapus file lama secara otomatis.
import aiofiles
import os
import asyncio
import time
async def clean_up(folder_path, days_old):
now = time.time()
cutoff_time = now - (days_old * 86400)
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.getmtime(file_path) < cutoff_time:
await aiofiles.os.remove(file_path)
print(f"Deleted {filename}")
folder = "/path/to/your/folder"
asyncio.run(clean_up(folder, 30))
9. Resize Gambar Otomatis
Gunakan library Pillow untuk mengubah ukuran gambar dalam jumlah banyak sekaligus.
from PIL import Image
import os
import asyncio
import re
from concurrent.futures import ProcessPoolExecutor
def resize_image(filename, width, height):
img = Image.open(filename)
img = img.resize((width, height))
img.save(f"resized_{filename}")
return f"Resized {filename}"
async def resize_images(folder_path, width, height):
with ProcessPoolExecutor() as executor:
loop = asyncio.get_event_loop()
tasks = []
for filename in os.listdir(folder_path):
search = re.search(r"\.(jp(e)g|png)$", filename)
if search:
tasks.append(
loop.run_in_executor(
executor,
resize_image,
os.path.join(folder_path, filename),
width,
height,
)
)
results = await asyncio.gather(*tasks)
print(results)
folder = "/path/to/your/images"
asyncio.run(resize_images(folder, 800, 600))
10. Script Python Untuk Entry Data ke Excel
Otomatiskan pengisian data ke Excel dengan library openpyxl.
from openpyxl import Workbook
def create_excel(data):
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
wb.save("data.xlsx")
print("Excel file created successfully!")
data = [
["Nama", "Umur", "Kota"],
["Bambang", 30, "Malang"],
["Ana", 25, "Semarang"],
]
create_excel(data)
Kesimpulan
Ini hanyalah beberapa contoh dari apa yang dapat dilakukan Python untuk mengotomatiskan pekerjaan harianmu. Dengan sintaks yang sederhana dan library yang lengkap, Python dapat menangani hampir semua tugas yang diberikan. Mulailah dengan otomatisasi Python hari ini, dan biarkan Python menanganinya!
