20 个 Python 非常实用的自动化脚本
用Python编写简单自动化任务脚本 #生活乐趣# #日常生活趣事# #生活趣味分享# #科技小发明#
假设你已经用 Python 编码一段时间了,并且在编码方面非常自信,但我还是建议你认真阅读下本次推文。
这里有 20 个 Python 脚本,如果你都掌握了,相信你的同事将会对你印象深刻、将那些看似不可自动化的事情自动化完成,并解决你甚至不知道的问题。
1. 文件重复查找器
是否曾经查看过硬盘并想知道,为什么我只剩下 100MB?有一种非常讨厌的事情就是文件重复。以下是查找重复文件和删除它们的脚本:
import os import hashlib def hash_file(filename): h = hashlib.md5() with open(filename, 'rb') as file: while chunk := file.read(8192): h.update(chunk) return h.hexdigest() def find_duplicates(folder): hashes = {} for dirpath, _, filenames in os.walk(folder): for f in filenames: full_path = os.path.join(dirpath, f) file_hash = hash_file(full_path) if file_hash in hashes: print(f"Duplicate found: {full_path} == {hashes[file_hash]}") else: hashes[file_hash] = full_path find_duplicates('/path/to/your/folder')
ps:主要不要在系统文件夹上盲目运行此操作。
我曾经在旧项目文件夹上运行这个程序后,在不到 10 分钟的时间内释放了 10GB 的空间。
2. 自动整理下载文件夹
我们基本不会认真整理下载文件夹内的内容,下面是一个可以整齐地组织所有内容的脚本:
import os import shutil def organize_folder(folder): file_types = { 'Images': ['.jpeg', '.jpg', '.png', '.gif'], 'Videos': ['.mp4', '.avi', '.mov'], 'Documents': ['.pdf', '.docx', '.txt'], 'Archives': ['.zip', '.rar'] } for filename in os.listdir(folder): file_path = os.path.join(folder, filename) if os.path.isfile(file_path): ext = os.path.splitext(filename)[1].lower() for folder_name, extensions in file_types.items(): if ext in extensions: target_folder = os.path.join(folder, folder_name) os.makedirs(target_folder, exist_ok=True) shutil.move(file_path, os.path.join(target_folder, filename)) print(f'Moved {filename} to {folder_name}') organize_folder('/path/to/Downloads')
相信你也一样,根本没有时间手动组织文件,那就用起来吧。
3. 批量图像调整器
正在处理需要调整图像大小的项目?下面介绍如何轻松批量调整图像大小:
from PIL import Image import os def batch_resize(folder, width, height): for filename in os.listdir(folder): if filename.endswith(('.jpeg', '.jpg', '.png')): 优势 = Image.open(os.path.join(folder, filename)) 优势 = 优势.resize((width, height)) 优势.save(os.path.join(folder, f"resized_{filename}")) print(f'Resized {filename}') batch_resize('/path/to/images', 800, 600)
当你的领导想要 “在 5 分钟内裁剪并调整这些图像的大小” 时,这非常适合。
4. 实时天气通知
每小时获取实时天气更新,再也不会忘记带伞:
import requests import time API_KEY = 'your_api_key' CITY = 'New York' def get_weather(): url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}" response = requests.get(url) data = response.json() return data['weather'][0]['description'], data['main']['temp'] - 273.15 while True: weather, temp = get_weather() print(f"Current weather in {CITY}: {weather}, {temp:.2f}°C") time.sleep(3600) # Run every hour
虽然天气app使用起来也比较方便,但这也是一种装x的方式,哈哈哈。
5. 发送电子邮件
如果你对某个特定的博客网站很着迷,但又不想经常检查它,这里有一个 Python 脚本,它可以将最新的reddit 帖子直接发送到你的收件箱:
import smtplib import requests def send_email(subject, body): from_addr = 'your_email@example.com' to_addr = 'your_email@example.com' msg = f"Subject: {subject}\n\n{body}" with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login('your_email@example.com', 'your_password') server.sendmail(from_addr, to_addr, msg) def get_reddit_posts(subreddit): url = f"https://www.reddit.com/r/{subreddit}/new.json" headers = {'User-agent': 'Mozilla/5.0'} response = requests.get(url, headers=headers) data = response.json() return [post['data']['title'] for post in data['data']['children']] posts = get_reddit_posts('python') send_email('Latest Reddit Posts', '\n'.join(posts))
自动化可以节省大量时间。
6. 将任何网页转换为电子书
此脚本将您最喜欢的文章转换成电子书格式,非常适合离线阅读:
import requests from bs4 import BeautifulSoup from ebooklib import epub def create_ebook(url, book_title): response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') book = epub.EpubBook() book.set_title(book_title) chapter = epub.EpubHtml(title='Chapter 1', file_name='chap_01.xhtml') chapter.content = soup.prettify() book.add_item(chapter) book.spine = ['nav', chapter] epub.write_epub(f'{book_title}.epub', book, {}) create_ebook('https://example.com/your-favorite-article', 'My eBook')
7. 将文本转换为语音
听书比看书来得轻松,此脚本可将文本转换为语音:
import pyttsx3 def text_to_speech(text): engine = pyttsx3.init() engine.say(text) engine.runAndWait() text_to_speech('Hello World, Python is amazing!')
Ps:这个技术恐怕只能拿来炫技,使用它来发现错误或者只是让自己在阅读时休息一下,不是非常实用。
8. 检查网站可用性
想知道你的网站是否瘫痪?这里有一个简单的脚本可以帮你检查:
import requests def is_website_online(url): try: response = requests.get(url) return response.status_code == 200 except: return False print(is_website_online('https://example.com'))
如果你自建了一个网站,有一天当你醒来发现你的网站已瘫痪 4 个小时时,这个时候就会发现这个代码的好处了。
9. 跟踪加密货币价格
使用此脚本跟踪你最喜欢的加密货币价格:
import requests def get_crypto_price(crypto): url = f"https://api.coindesk.com/v1/bpi/currentprice/{crypto}.json" response = requests.get(url) data = response.json() return data['bpi']['USD']['rate'] print(get_crypto_price('BTC'))
10.下载完成后关闭电脑
再也不用等着下载完毕在关电脑了。让你的计算机自行处理。此脚本会在下载完成后关闭 PC:
import os import time def check_downloads(): while True: if not os.listdir('/path/to/downloads'): print("Shutting down...") os.system("shutdown /s /t 1") time.sleep(60) check_downloads()
11. 使用密码保护你的脚本
这里有一个有趣的例子:用密码保护你的脚本,这样就没有人可以在未经许可的情况下运行它们:
import getpass password = getpass.getpass('Enter your password: ') if password != 'secret': print('Access Denied') exit() else: print('Access Granted') # Your protected code here
Ps:将其与加密方法结合,可获得双重保护。
12. 监控计算机的 CPU 使用情况
留意 CPU 温度和使用情况:
import psutil def monitor_cpu(): print(f"CPU usage: {psutil.cpu_percent()}%") print(f"Memory usage: {psutil.virtual_memory().percent}%") monitor_cpu()
因为CPU过热绝对不是什么好事。当然,也有专门应用可以直接使用,但作为编程大佬的你,直接上代码不是很酷么!
13. 将 PDF 转换为文本
如果你经常处理 PDF,此脚本将为提取文本提供一些思路:
import PyPDF2 def pdf_to_text(pdf_file): reader = PyPDF2.PdfReader(pdf_file) text = '' for page in reader.pages: text += page.extract_text() return text print(pdf_to_text('example.pdf'))
现在你可以轻松提取关键信息,而无需无休止地复制粘贴。
14. 生成二维码
为任何 URL 或文本创建二维码:
import qrcode def generate_qr(text, filename): code = qrcode.make(text) code.save(f"{filename}.png") generate_qr('https://example.com', 'my_qr_code')
谁知道二维码可以这么简单?
15. 下载 YouTube 视频
在几秒钟内下载您喜爱的 YouTube 视频:
import yt_dlp def download_video(url): # yt-dlp 的选项 ydl_opts = { 'format' : 'best' , # 下载最佳可用质量 'outtmpl' : '%(title)s.%(ext)s' , # 将文件名设置为视频标题 'noplaylist' : True , # 如果 URL 是播放列表的一部分,则下载单个视频 'quiet' : False , # 在控制台中显示下载进度 'ignoreerrors' : True , # 即使遇到错误也继续 'no_warnings' : True , # 抑制警告 } try : # 使用 yt-dlp 下载视频 with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) print ( "下载已成功完成。" ) except Exception as e: print ( f"发生错误:{e}" ) # 用所需的 YouTube 视频 URL 替换 download_video('https://www.youtube.com/watch?v=_v7ksOgFn-w' )
请记住,负责任地下载!
16. 创建随机强密码
使用此脚本生成强随机密码:
import string import random def generate_password(length): chars = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(chars) for _ in range(length)) print(generate_password(16))
再也不用为想个密码而头疼了。
17. 获取实时股票价格
使用此快速脚本跟踪实时股票价格:
import requests def get_stock_price(symbol): url = f"https://finnhub.io/api/v1/quote?symbol={symbol}&token=your_api_key" response = requests.get(url) data = response.json() return data['c'] print(get_stock_price('AAPL'))
实现了边写代码,边炒股了!
18. 创建一个简单的聊天机器人
制作自己的聊天机器人:
import random def chatbot(): responses = ['Hello!', 'How can I help you?', 'Goodbye!'] while True: user_input = input("You: ") if user_input.lower() == 'bye': print("Chatbot: Goodbye!") break print(f"Chatbot: {random.choice(responses)}") chatbot()
你的个人助理,仅需几行代码即可创建。当然,你也可以通过部署一个大语言模型为驱动,部署你的智能聊天机器人,只要你有足够的显卡资源。
19. 用计步器跟踪每日步数
除了使用手表跟踪步数,作为一编程大佬,我们还可以使用 Python 获取步数:
import fitbit def get_daily_steps(token): client = fitbit.Fitbit('client_id', 'client_secret', oauth2_token=token) steps = client.activities()['summary']['steps'] return steps print(f"Steps today: {get_daily_steps('your_token')}")
Python 除了不能帮你生孩子,真实无所不能!
20. 创建待办事项清单
一个简单的待办事项清单,因为我们的生活都需要一些秩序:
import json def add_task(task): with open('todo.json', 'r+') as file: tasks = json.load(file) tasks.append(task) file.seek(0) json.dump(tasks, file) add_task('Publish Medium article')
以 Pythonic 方式掌握最新动态。
网址:20 个 Python 非常实用的自动化脚本 https://www.yuejiaxmz.com/news/view/445599
相关内容
5个实用的自动化Python脚本五个方便好用的Python自动化脚本
轻松实现日常任务自动化的6个Python脚本
6个Python脚本,轻松实现日常任务自动化
【源码】10 个用于日常自动化的 Python 脚本!
10个Python脚本,轻松实现日常任务自动化!
解决日常问题的 10 个 Python 自动化脚本
十个Python脚本,轻松实现日常任务自动化
10个Python脚本轻松实现日常任务自动化
10个Python脚本自动化日常任务