搜尋
首頁後端開發Python教學自動執行日常任務的 Python 腳本

Python Scripts to Automate Your Daily Tasks

每個人都必須擁有的收藏......

Python 憑藉其簡單性和強大的庫改變了我們實現自動化的方式。無論您是技術愛好者、忙碌的專業人士,還是只是想簡化日常工作,Python 都可以幫助您自動執行重複性任務,節省時間並提高效率。這裡收集了 10 個基本的 Python 腳本,可以幫助您自動化日常生活的各個方面。

讓我們開始吧!


1.自動發送電子郵件

手動發送電子郵件,尤其是重複發送的電子郵件,可能非常耗時。使用 Python 的 smtplib 函式庫,您可以輕鬆地自動化此過程。無論是發送提醒、更新還是個人化訊息,這個腳本都可以處理。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(receiver_email, subject, body):
    sender_email = "your_email@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
            print("Email sent successfully!")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
send_email("receiver_email@example.com", "Subject Here", "Email body goes here.")

此腳本可以輕鬆整合到更大的工作流程中,例如發送報告或警報。

2.檔案管理器

如果您的下載資料夾一片混亂,那麼這個腳本適合您。它按擴展名組織文件,將它們整齊地放入子資料夾中。不再需要篩選數十個文件來找到您需要的內容!

import os
from shutil import move

def organize_folder(folder_path):
    for file in os.listdir(folder_path):
        if os.path.isfile(os.path.join(folder_path, file)):
            ext = file.split('.')[-1]
            ext_folder = os.path.join(folder_path, ext)
            os.makedirs(ext_folder, exist_ok=True)
            move(os.path.join(folder_path, file), os.path.join(ext_folder, file))

# Example usage
organize_folder("C:/Users/YourName/Downloads")

此腳本對於管理 PDF、映像或文件等文件特別有用。

3.網頁抓取新聞頭條

透過從您最喜愛的網站抓取頭條新聞來了解最新新聞。 Python 的「requests」和「BeautifulSoup」函式庫使這個過程變得無縫。

import requests
from bs4 import BeautifulSoup

def fetch_headlines(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    headlines = [h.text for h in soup.find_all('h2', class_='headline')]
    return headlines

# Example usage
headlines = fetch_headlines("https://news.ycombinator.com/")
print("\n".join(headlines))

無論您是新聞迷還是需要工作更新,此腳本都可以安排每天運行。

4.每日天氣通知

從天氣更新開始新的一天!此腳本使用 OpenWeatherMap API 取得您所在城市的天氣預報並顯示溫度和天氣預報。

import requests

def get_weather(city):
    api_key = "your_api_key"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url).json()
    if response.get("main"):
        temp = response['main']['temp']
        weather = response['weather'][0]['description']
        print(f"The current weather in {city} is {temp}°C with {weather}.")
    else:
        print("City not found!")

# Example usage
get_weather("New York")

只需稍加調整,您就可以讓它直接向您的手機發送通知。

5.自動化社群媒體貼文

使用 Python 安排社群媒體貼文變得輕而易舉。使用“tweepy”庫以程式設計方式發布推文。

import tweepy

def post_tweet(api_key, api_key_secret, access_token, access_token_secret, tweet):
    auth = tweepy.OAuthHandler(api_key, api_key_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    api.update_status(tweet)
    print("Tweet posted!")

# Example usage
post_tweet("api_key", "api_key_secret", "access_token", "access_token_secret", "Hello, Twitter!")

非常適合想要提前規劃貼文的社群媒體管理者和內容創作者。

6.PDF 到文字轉換

手動從 PDF 中提取文字非常繁瑣。該腳本使用“PyPDF2”庫簡化了流程。

from PyPDF2 import PdfReader

def pdf_to_text(file_path):
    reader = PdfReader(file_path)
    text = ""
    for page in reader.pages:
        text += page.extract_text()
    return text

# Example usage
print(pdf_to_text("sample.pdf"))

非常適合歸檔或分析文字較多的文件。

7.使用 CSV 進行費用追蹤

透過將費用記錄到 CSV 檔案中來追蹤您的費用。此腳本可協助您維護數位記錄,以便稍後分析。

import csv

def log_expense(file_name, date, item, amount):
    with open(file_name, mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([date, item, amount])
        print("Expense logged!")

# Example usage
log_expense("expenses.csv", "2024-11-22", "Coffee", 4.5)

將其變成一種習慣,您就會清楚地了解自己的消費模式。

8.自動化桌面通知

您的電腦上需要提醒或警報嗎?該腳本使用“plyer”庫發送桌面通知。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(receiver_email, subject, body):
    sender_email = "your_email@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
            print("Email sent successfully!")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
send_email("receiver_email@example.com", "Subject Here", "Email body goes here.")

非常適合任務管理和事件提醒。

9.網站可用性檢查

使用這個簡單的腳本監控您的網站或喜愛的平台的正常運作時間。

import os
from shutil import move

def organize_folder(folder_path):
    for file in os.listdir(folder_path):
        if os.path.isfile(os.path.join(folder_path, file)):
            ext = file.split('.')[-1]
            ext_folder = os.path.join(folder_path, ext)
            os.makedirs(ext_folder, exist_ok=True)
            move(os.path.join(folder_path, file), os.path.join(ext_folder, file))

# Example usage
organize_folder("C:/Users/YourName/Downloads")

對網頁開發人員和企業主有用。

10.自動化資料備份

再也不用擔心遺失重要文件了。該腳本會自動將檔案備份到指定位置。

import requests
from bs4 import BeautifulSoup

def fetch_headlines(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    headlines = [h.text for h in soup.find_all('h2', class_='headline')]
    return headlines

# Example usage
headlines = fetch_headlines("https://news.ycombinator.com/")
print("\n".join(headlines))

每週或每天運行一次,以確保您的資料始終安全。


這 10 個腳本示範了 Python 如何處理重複性任務並簡化您的日常生活。從管理文件到在社群媒體上發布,自動化開啟了無限的可能性。選擇一個腳本,對其進行自訂,並將其整合到您的工作流程中。很快,您就會想知道如果沒有 Python 自動化,您是如何生活的!

你會先嘗試哪一個?

請在評論部分告訴我們!

以上是自動執行日常任務的 Python 腳本的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:對於循環,最完整的指南Python:對於循環,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

python concatenate列表到一個字符串中python concatenate列表到一個字符串中May 09, 2025 am 12:02 AM

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中