Hiện nay, tự động hóa không còn là một tùy chọn mà đã trở thành một yêu cầu thiết yếu giúp bạn tiết kiệm thời gian, tăng hiệu suất làm việc và giảm thiểu sai sót. Nếu bạn cảm thấy mệt mỏi với những công việc lặp đi lặp lại như đổi tên tệp, gửi email hàng loạt, thu thập dữ liệu từ web hay sao lưu tài liệu, thì Python chính là công cụ lý tưởng để giúp bạn biến những tác vụ tẻ nhạt thành quy trình tự động mượt mà.
Trong bài viết này, hãy cùng VietnamWorks inTECH khám phá 25 script Python hàng đầu giúp bạn tăng tốc công việc hằng ngày, từ đơn giản đến nâng cao.
1. Tự động gửi email
Sử dụng Python để gửi email kèm tệp đính kèm.
Thư viện: smtplib, email
import smtplibfrom email.mime.text import MIMETextdef send_email(subject, body, to_email):smtp_server = "smtp.gmail.com"smtp_port = 587sender_email = "your_email@gmail.com"sender_password = "your_password"msg = MIMEText(body)msg['Subject'] = subjectmsg['From'] = sender_emailmsg['To'] = to_emailwith smtplib.SMTP(smtp_server, smtp_port) as server:server.starttls()server.login(sender_email, sender_password)server.sendmail(sender_email, to_email, msg.as_string()) |
2. Web Scraping để trích xuất dữ liệu
Tự động trích xuất dữ liệu từ các trang web.
Thư viện: requests, BeautifulSoup
import requestsresponse = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')print(soup.title.string) |
3. Tải xuống các tập tin từ Internet
Tự động tải xuống tệp từ URL.
Thư viện: requests
import osimport shutildef sort_files(directory):for file in os.listdir(directory):ext = file.split('.')[-1]folder = os.path.join(directory, ext)os.makedirs(folder, exist_ok=True)shutil.move(os.path.join(directory, file), os.path.join(folder, file)) |
4. Tự động sắp xếp tập tin
Tự động sắp xếp các tập tin theo phần mở rộng.
Thư viện: os,shutil
import osimport shutildef sort_files(directory):for file in os.listdir(directory):ext = file.split('.')[-1]folder = os.path.join(directory, ext)os.makedirs(folder, exist_ok=True)shutil.move(os.path.join(directory, file), os.path.join(folder, file)) |
5. Đổi tên nhiều tập tin
Đổi tên hàng loạt tập tin trong một thư mục.
Thư viện: os
import osdef rename_files(directory, prefix):for i, file in enumerate(os.listdir(directory)):os.rename(os.path.join(directory, file), os.path.join(directory, f"{prefix}_{i}.txt")) |
6. Tự động tạo bản sao lưu
Sao lưu các tập tin quan trọng vào file zip.
Thư viện: shutil
import shutildef create_backup(source_dir, backup_file):shutil.make_archive(backup_file, 'zip', source_dir) |
7. Tự động hóa bài đăng trên mạng xã hội
Lên lịch đăng tweet/bài viết.
Thư viện: tweepy ,facebook-sdk
import tweepydef post_tweet(api_key, api_secret, access_token, access_secret, tweet):auth = tweepy.OAuthHandler(api_key, api_secret)auth.set_access_token(access_token, access_secret)api = tweepy.API(auth)api.update_status(tweet) |
8. Tự động hóa dữ liệu bảng tính
Đọc/ghi tệp Excel.
Thư viện: openpyxl
import openpyxldef read_excel(file):wb = openpyxl.load_workbook(file)sheet = wb.activefor row in sheet.iter_rows():print([cell.value for cell in row]) |
9. Tự động dịch văn bản
Dịch văn bản bằng API.
Thư viện: googletrans
from googletrans import Translatordef translate_text(text, dest_lang):translator = Translator()return translator.translate(text, dest=dest_lang).text |
10. Tự động hóa thao tác PDF
Ghép, tách hoặc trích xuất văn bản từ tệp PDF.
Thư viện: PyPDF2
from PyPDF2 import PdfReader, PdfMergerdef merge_pdfs(pdf_list, output):merger = PdfMerger()for pdf in pdf_list:merger.append(pdf)merger.write(output) |
11. Tự động xử lý hình ảnh
Thay đổi kích thước, xoay hoặc thêm watermarks.
Thư viện: Pillow
from PIL import Imagedef resize_image(image_path, output_path, size):with Image.open(image_path) as img:img.resize(size).save(output_path) |
12. Tự động giám sát trang web
Thông báo khi trang web được cập nhật.
Thư viện: requests, time
import requestsimport timedef monitor_website(url, interval):prev_content = Nonewhile True:response = requests.get(url)if response.text != prev_content:print("Website updated!")prev_content = response.texttime.sleep(interval) |
13. Tự động sao lưu cơ sở dữ liệu
Sao lưu cơ sở dữ liệu như MySQL.
Thư viện: subprocess
import subprocessdef backup_mysql(user, password, db_name, output):cmd = f"mysqldump -u {user} -p{password} {db_name} > {output}"subprocess.run(cmd, shell=True) |
14. Tự động hóa thông báo Slack
Gửi tin nhắn Slack theo thiết lập.
Thư viện: slack-sdk
from slack_sdk import WebClientdef send_slack_message(token, channel, text):client = WebClient(token=token)client.chat_postMessage(channel=channel, text=text) |
15. Tự động cập nhật thời tiết
Lấy dữ liệu thời tiết.
Thư viện: requests
import requestsdef get_weather(api_key, city):url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"return requests.get(url).json() |
16. Tự động chuyển văn bản thành giọng nói
Chuyển đổi văn bản thành giọng nói.
Thư viện: pyttsx3
import pyttsx3def text_to_speech(text):engine = pyttsx3.init()engine.say(text)engine.runAndWait() |
17. Tự động chuyển đổi tiền tệ
Chuyển đổi tiền tệ bằng API.
Thư viện: forex-python
from forex_python.converter import CurrencyRatesdef convert_currency(amount, from_currency, to_currency):c = CurrencyRates()return c.convert(from_currency, to_currency, amount) |
18. Tự động lập lịch tác vụ
Lên lịch tác vụ Python.
Thư viện: schedule
import scheduleimport timedef task():print("Task running!")schedule.every().day.at("10:00").do(task)while True:schedule.run_pending()time.sleep(1) |
19. Tự động hóa thông báo
Đẩy thông báo tới điện thoại của bạn.
Thư viện: pushbullet
from pushbullet import Pushbulletdef send_notification(api_key, title, body):pb = Pushbullet(api_key)pb.push_note(title, body) |
20. Tự động dọn dẹp thư mục
Xóa các tập tin cũ trong một thư mục.
Thư viện: os,time
import osimport timedef cleanup(directory, days):now = time.time()for file in os.listdir(directory):filepath = os.path.join(directory, file)if os.stat(filepath).st_mtime < now - days * 86400:os.remove(filepath) |
21. Tự động theo dõi giá cổ phiếu
Lấy giá cổ phiếu.
Thư viện: yfinance
import yfinance as yfdef get_stock_price(ticker):stock = yf.Ticker(ticker)return stock.history(period="1d")["Close"] |
22. Tự động tạo mã QR
Tạo mã QR cho văn bản hoặc URL.
Thư viện: qrcode
import qrcodedef generate_qr(data, filename):qr = qrcode.make(data)qr.save(filename) |
23. Tự động hóa mô phỏng nhấn phím
Tự động nhấn phím trên bàn phím.
Thư viện: pyautogui
import pyautoguidef automate_typing(text):pyautogui.typewrite(text) |
24. Tự động hóa các hoạt động Git
Tự động git push/pull.
Thư viện: subprocess
import subprocessdef git_push(message):subprocess.run(["git", "add", "."])subprocess.run(["git", "commit", "-m", message])subprocess.run(["git", "push"]) |
25. Tự động theo dõi thời gian
Theo dõi thời gian bạn dành cho nhiệm vụ.
Thư viện: time
import timestart_time = time.time()# Do some workprint("Time spent:", time.time() - start_time) |
Lời kết
Với 25 script Python hữu ích mà chúng ta vừa tìm hiểu, bạn có thể tự động hóa nhiều tác vụ nhàm chán, giúp công việc trở nên nhanh chóng, hiệu quả và giảm bớt công sức thủ công. Không quan trọng bạn là người mới học lập trình hay một chuyên gia, việc sử dụng Python để tự động hóa sẽ mang lại lợi ích to lớn trong công việc và cuộc sống hàng ngày.




